Closed alex-vasenin closed 7 months ago
I think you'll have to wait for Swift 6.0 where, with https://github.com/apple/swift-evolution/blob/main/proposals/0421-generalize-async-sequence.md implemented, you'll be able to spell the return type as:
some AsyncSequence<Notification, any Error>
or maybe even
some AsyncSequence<Notification, Never>
assuming that the associated type NotificationCenter.Notifications.Failure
gets defined by Apple as Never
as I believe it should.
Thank you for promptly reply. So much is going on in Swift Evolution! It's good they eventually include it in the language itself.
In the meanwhile, do you think this naive solution will suffice (performance is not an issue):
extension NotificationCenter {
private func typeErasedNotifications(_ name: Notification.Name) -> AsyncStream<Notification.Name> {
AsyncStream { continuation in
let task = Task {
for await notification in self.notifications(named: name) {
continuation.yield(notification.name)
}
}
continuation.onTermination = { _ in task.cancel() }
}
}
}
I would not recommend that pattern since it removes the back pressure propagation and buffers potentially unlimited data in the intermediate stream. Instead you can write yourself an AnyAsynStream
wrapper.
Instead you can write yourself an
AnyAsyncStream
wrapper.
I tried to wrap my head around Swift type system for about an hour and it wasn't fruitful. Could you point me to a good example of similar implementation?
Something like this should work: https://github.com/vsanthanam/AnyAsyncSequence
That's great! Thank you!
TLDR
some AsyncSequence
will be available in Swift 6
In the meanwhile we can use something like https://github.com/vsanthanam/AnyAsyncSequence
I think type erasure for complicated
AsyncSequence
would be a nice addition to this package. There are some discussions about this feature on the net, for example, here and here.I personally encountered this need while searching for solution for merging two
AsyncSequence
fromNotificationCenter
. Currently this code produces warning withSWIFT_STRICT_CONCURRENCY = Complete
even though I use the solution recommended inNotificationCenter.notifications(named:object:)
documentation:And the type annotations are obviously quite ugly.