Skip to content

Instantly share code, notes, and snippets.

@phucnm
Created November 19, 2019 03:22
Show Gist options
  • Save phucnm/8f988b9edd37c592e8d7d1a79f256c2a to your computer and use it in GitHub Desktop.
Save phucnm/8f988b9edd37c592e8d7d1a79f256c2a to your computer and use it in GitHub Desktop.
Rx extension for CFNotification
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