Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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