Created
June 4, 2019 07:52
-
-
Save kastiglione/8c0cd3ec7535ec4bf3f9affa4775e2d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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