Last active
May 12, 2024 09:55
-
-
Save malhal/71d472863f2cbd0f28e7e91f96264690 to your computer and use it in GitHub Desktop.
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 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