Merging two notification observers in RxSwift

Milan Cermak picture Milan Cermak · Apr 1, 2016 · Viewed 9.9k times · Source

I have this piece of code:

let appActiveNotifications: [Observable<NSNotification>] = [
    NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification),
    NSNotificationCenter.defaultCenter().rx_notification(Constants.AppRuntimeCallIncomingNotification)
]

appActiveNotifications.merge()
  .takeUntil(self.rx_deallocated)
  .subscribeNext() { [weak self] _ in
  // notification handling
}
.addDisposableTo(disposeBag)

It's supposed to listen to either of the specified notifications and handle when any of them is triggered.

However this does not compile. I get the following error:

Value of type '[Observable<NSNotification>]' has no member 'merge'

How should I merge these two signals to one then?

Answer

David Chavez picture David Chavez · Apr 1, 2016

.merge() combines multiple Observables so you'll want to do appActiveNotifications.toObservable() then call .merge() on it

Edit: Or as the example in the RxSwift's playground, you can use Observable.of() then use .merge() on it; like so:

let a = NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification)
let b = NSNotificationCenter.defaultCenter().rx_notification(Constants.AppRuntimeCallIncomingNotification)

Observable.of(a, b)
  .merge()
  .takeUntil(self.rx_deallocated)
  .subscribeNext() { [weak self] _ in
     // notification handling
  }.addDisposableTo(disposeBag)