Created
July 2, 2019 11:57
-
-
Save el-hoshino/7c0fcdc9f77711536011718b21999b53 to your computer and use it in GitHub Desktop.
Viewにassign(_, to:)メソッド作ってみた #swiftui #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SwiftUI | |
import Combine | |
protocol UsecaseProtocol: AnyObject { | |
var intPublisher: AnyPublisher<Int, Never> { get } | |
func reset() | |
} | |
struct ContentView : View { | |
private let usecase: UsecaseProtocol | |
@State var int: Int = 0 | |
init(usecase: UsecaseProtocol) { | |
self.usecase = usecase | |
} | |
var body: some View { | |
Button.init(action: { [unowned usecase] in | |
usecase.reset() | |
}, label: { | |
Text("\(int)") | |
}) | |
.assign(usecase.intPublisher, to: $int) | |
} | |
} | |
#if DEBUG | |
let someUsecase = SomeUsecase() | |
struct ContentView_Previews : PreviewProvider { | |
static var previews: some View { | |
ContentView(usecase: someUsecase) | |
} | |
} | |
#endif | |
private extension View { | |
func assign <P> (_ publisher: P, to state: Binding<P.Output>) -> SubscriptionView<Publishers.ReceiveOn<P, DispatchQueue>, Self> where P : Publisher, P.Failure == Never { | |
return onReceive(publisher.receive(on: DispatchQueue.main)) { result in | |
state.value = result | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment