在 RxSwift 中合并两个通知观察者

Merging two notification observers in RxSwift

我有这段代码:

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)

它应该监听任何一个指定的通知并在其中任何一个被触发时进行处理。

然而这并不能编译。我收到以下错误:

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

那我应该如何将这两个信号合并为一个?

.merge() 结合了多个 Observables 所以你会想做 appActiveNotifications.toObservable() 然后调用 .merge()

编辑: 或者像RxSwift's playground里的例子,你可以先用Observable.of()再用.merge()就可以了;像这样:

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)