Created
November 19, 2019 03:22
-
-
Save phucnm/8f988b9edd37c592e8d7d1a79f256c2a to your computer and use it in GitHub Desktop.
Rx extension for CFNotification
This file contains 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
extension Reactive where Base: NSObject { | |
func cfNotification(notificationName: CFString) -> Observable<Notification> { | |
let cfNotificationName = CFNotificationName(notificationName) | |
let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter() | |
CFNotificationCenterAddObserver( | |
notificationCenter, | |
Unmanaged.passRetained(self.base).toOpaque(), | |
{ ( | |
center: CFNotificationCenter?, | |
observer: UnsafeMutableRawPointer?, | |
name: CFNotificationName?, | |
object: UnsafeRawPointer?, | |
userInfo: CFDictionary? | |
) in | |
if let name = name { | |
NotificationCenter.default.post(name: Notification.Name(name.rawValue as String), object: nil) | |
} | |
}, | |
notificationName, | |
nil, | |
CFNotificationSuspensionBehavior.deliverImmediately | |
) | |
return NotificationCenter.default.rx.notification(Notification.Name(notificationName as String)) | |
.do(onDispose: { | |
CFNotificationCenterRemoveObserver( | |
notificationCenter, | |
Unmanaged.passRetained(self.base).toOpaque(), | |
cfNotificationName, nil | |
) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment