Code: Select all
import SwiftUI
struct ContentView: View {
var body: some View {
ParentView()
}
}
struct ParentView: View {
@State var id = 0
var body: some View {
VStack {
Button {
id+=1
} label: {
Text("update id by 1")
}
TestView(id: id)
}
}
}
struct TestView: View {
var sequence = DoubleGenerator()
let id: Int
var body: some View {
VStack {
Button {
sequence.next()
} label: {
Text("print next number").background(content: {
Color.green
})
}
Text("current id is \(id)")
}.task {
for await number in sequence.stream {
print("next number is \(number)")
}
}
}
}
final class DoubleGenerator {
private var current = 1
private let continuation: AsyncStream.Continuation
let stream: AsyncStream
init() {
var cont: AsyncStream.Continuation!
self.stream = AsyncStream { cont = $0 }
self.continuation = cont
}
func next() {
guard current >= 0 else {
continuation.finish()
return
}
continuation.yield(current)
current &*= 2
}
}
Ist das das erwartete Verhalten? Warum ist in onChange und Button der Verweis auf die Eigenschaften immer aktuell, in .task jedoch nicht?
Mobile version