Skip to content

Instantly share code, notes, and snippets.

@malhal
Last active May 12, 2024 09:55
Show Gist options
  • Save malhal/71d472863f2cbd0f28e7e91f96264690 to your computer and use it in GitHub Desktop.
Save malhal/71d472863f2cbd0f28e7e91f96264690 to your computer and use it in GitHub Desktop.
import SwiftUI
// AsyncObservableTest.ContentView() in your app struct
struct AsyncObservableTest {
@Observable
class Content {
var counter = 0
}
struct ContentView: View {
@State var content: Content?
@State var counterFromStream = 0
var body: some View {
NavigationStack {
if let content {
Button("Increment \(content.counter)") {
content.counter += 1
}
.buttonStyle(.borderedProminent)
Text("Counter from stream: \(counterFromStream, format: .number)")
.task {
let modelCounterDidChange = AsyncStream {
await withCheckedContinuation { continuation in
withObservationTracking {
let _ = content.counter
} onChange: {
continuation.resume()
}
}
// return content.counter // we couild insert the value in the stream but it makes the loop below more complicated
}
var iterator = modelCounterDidChange.makeAsyncIterator()
repeat {
counterFromStream = content.counter
} while await iterator.next() != nil
}
}
else {
Text("Initing object...")
}
}
.onAppear {
content = Content()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment