Search code examples
swiftrx-swiftreactivex

Merging two notification observers in RxSwift


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?


Solution

  • .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)