1

I would like to know below lines of code I mentioned NSNotificationCenter in swift 3.0 can be converted into RxSwif/RxCocoa

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image   
}
}
Rajesh
  • 124
  • 9

1 Answers1

9

I'm assuming you are asking how to do this in ReactiveCocoa. In ReactiveCocoa, all extensions are available via the .reactive member:

extension Notification.Name {
  static let myNotification = Notification.Name("myNotification")
}


NotificationCenter.default.reactive.notifications(forName: .myNotification)
  .take(duringLifetimeOf: self)
  .observeValues {
    if let image = $0.userInfo?["image"] as? UIImage {
      // do something with your image
    }
}


NotificationCenter.default.post(name: .myNotification, object: nil, userInfo: ["image": image])

Edit: Thanks @jjoelson for mentioning disposal of the observation.

MeXx
  • 3,357
  • 24
  • 39
  • I think this needs to manually disposed of, so I would add something like `.take(duringLifetimeOf: self)` prior to `.observeValues`, assuming `self` is the object processing the notification. – jjoelson Nov 20 '17 at 16:23