11

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?

Milan Cermak
  • 7,476
  • 3
  • 44
  • 59

1 Answers1

26

.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)
David Chavez
  • 381
  • 3
  • 5
  • I want to merge 2 different type of Observers. Any idea how to achieve? This is what I'm trying to do. http://stackoverflow.com/questions/39050059/rxswift-merge-different-kind-of-observables – Swift Hipster Aug 20 '16 at 04:01
  • You can't merge 2 different types of Observables. You have to convert on of them or both to make a match ! – nverinaud Dec 08 '16 at 13:06
  • @SwiftHipster you can use `zip` to get both results and merge it manually – Daniel Gomez Rico Feb 28 '17 at 15:12
  • if it's possible, map them to the same type, e.g. `NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification).map({ _ in true}_` – Shahar Apr 03 '17 at 10:49