Skip to content

Instantly share code, notes, and snippets.

@kastiglione
Created June 4, 2019 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kastiglione/8c0cd3ec7535ec4bf3f9affa4775e2d1 to your computer and use it in GitHub Desktop.
Save kastiglione/8c0cd3ec7535ec4bf3f9affa4775e2d1 to your computer and use it in GitHub Desktop.
func observeNotifications(name: NSNotification.Name) -> AnyPublisher<Notification, Never> {
return Publishers.Deferred<AnyPublisher<Notification, Never>> {
var observer: NSObjectProtocol?
return AnyPublisher { subscriber in
observer = NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { notification in
_ = subscriber.receive(notification)
}
}
.handleEvents(receiveCancel: {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
})
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func printNotifications<P: Publisher>(_ notifications: P) where P.Output == Notification, P.Failure == Never {
notifications.subscribe(AnySubscriber(receiveValue: { (notification: Notification) in
print(notification)
return .unlimited
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment