Created
March 13, 2022 06:58
-
-
Save notoroid/72a3491a6042369d3277d5c89762560e to your computer and use it in GitHub Desktop.
This file contains 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 SwiftUI | |
import Combine | |
// original code for CancellerWrapper was posted on @Cockscomb cockscomb's blog post. https://cockscomb.hatenablog.com/entry/2021/09/26/103128 | |
class CancellerWrapper<Wrapped> { | |
var value: Wrapped | |
init(_ value: Wrapped) { self.value = value } | |
} | |
class SimpleModel: UIResponder, ObservableObject { | |
struct State { | |
var items: [Int] | |
} | |
@Published var state = State(items: []) | |
} | |
struct ContentView: View { | |
@StateObject var simpleModel: SimpleModel | |
let cancellables: CancellerWrapper<Set<AnyCancellable>> = .init(Set<AnyCancellable>()) | |
var body: some View { | |
NavigationView { | |
Text("Simple Combine Framework SimpleCombineFrameworkTestbed") | |
.padding() | |
.onAppear { | |
simpleModel.$state.map(\.items).sink(receiveValue: { items in | |
print("items.count=\(items.count)") | |
}).store(in: &self.cancellables.value) | |
} | |
.navigationTitle(Text("Testbed")) | |
.navigationBarItems(trailing: | |
Button(action: { | |
simpleModel.state.items = [1,2,3,4,5] | |
}, label: { Text("Execute") }) | |
) | |
} | |
} | |
} | |
@main | |
struct SimpleCombineFrameworkTestbedApp: App { | |
var simpleModel = SimpleModel() | |
var body: some Scene { | |
WindowGroup { | |
ContentView(simpleModel: simpleModel) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var simpleModel = SimpleModel() | |
static var previews: some View { | |
ContentView(simpleModel: Self.simpleModel) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment