Hi, I am a newbie here and I have a proposition how to solve a problem when using Task.
I would love to await for some variable change inside Task to move further.
What I mean:
Task {
... for example here comes some complex code that is sending requests
through web socket to outer world,
response from websocket will change the variable result on this clas
but out of this scope
// with this line we are waiting for variable change with reasonable timeout
do {
try await @change(variable: self.result, timeout:10 sec)
} catch {
... timeout
print("we are waiting too long for server response")
}
}
You can currently solve this using an async sequence. A common pattern for this right now is doing the following:
static func main() async {
var cont = AsyncStream<Int>.Continuation!
let stream = AsyncStream<Int> { cont = $0 }
let continuation = cont
setupWebsocket(continuation)
for await element in stream {
// process the result
}
}
func setupWebsocket(continuation: AsyncStream<Int>.Continuation) {
// Setup the web socket and at some point call the following code
continuation.yield(2) // Yield your result
}
The other thing that might help here is the Observation pitch that is currently happening, this would allow you to observe the class and let the Task change it; however, importantly here is that you need make sure that everything is thread safe.