Hi,
I'm running into a problem with Stream.addCleanup
in the following code:
import Foundation
import SodiumSwift
struct FRP {
static func notification(forName name: Notification.Name?, object: Any?) -> SodiumSwift.Stream<Notification> {
let result = StreamSink<Notification>()
let observer = NotificationCenter.default.addObserver(forName: name, object: object, queue: nil) { [weak result] (notification) in
if let sink = result {
sink.send(notification)
}
}
return result.addCleanup(Listener(unlisten: {
DispatchQueue.main.async {
NotificationCenter.default.removeObserver(observer)
}
}))
}
}
What I'd like to achieve is the NotificationCenter
observer to be unregistered, when the returned stream is not referenced anymore. However, in my application, the unlisten
closure is never called, even though I remove all references to the FRP network referencing the stream returned by FRP.notification
.
I'm not sure if I'm running into a problem with reference counting cycles or a general misunderstanding of how addCleanup
should be used.
Thanks for any help!
The code requires this sodium-swift branch which adds a public Listener initializer.