Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notoroid/72a3491a6042369d3277d5c89762560e to your computer and use it in GitHub Desktop.
Save notoroid/72a3491a6042369d3277d5c89762560e to your computer and use it in GitHub Desktop.
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