Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
Milan Cermak Avatar asked Apr 01 '16 11:04

Milan Cermak


1 Answers

.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)
like image 153
David Chavez Avatar answered Nov 18 '22 05:11

David Chavez