Are there any updates on this in the documentation or the AsyncStream implementations?
I am currently struggling with the same problem of cooperative cancellation with async streams.
I have another example that I would like to handle with AsyncStream preferably.
I want to use AsyncStream for the OTA update of a Bluetooth device.
The user can abort/cancel the OTA update at any point, in code it could look like this:
// OTA update stream of events
func startUpdate() {
...
let updateTask = Task {
for await event in startUpdateStream() {
// handle event
}
}
...
}
func cancelUpdate() async {
updateTask.cancel()
// await update task as the cancellation takes time
await updateTask.value
}
The thing is that during the cancellation the iOS app needs to send a BLE command to stop the OTA update on the BLE device, the device needs to process that and respond that the OTA update was canceled. Only then does the iOS app know that the device is in an appropriate state after the OTA update cancellation.
That's why I would like to await updateTask.value
after the cancellation to be sure that the cancellation has been fully processed. The stream wouldn't be terminated with nil
or throw
right away as internally it would wait for the BLE device response that the OTA update has been canceled.
It would also better represent the intent to not allow to start of the OTA update again right after the cancellation (as the cancellation still might be in progress).
I'm not exactly sure if this would correctly model my requirement but it seems like another use case for a cooperative AsyncStream cancellation.