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

Mil*_*mak 10 swift rx-swift reactivex

我有这段代码:

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)
Run Code Online (Sandbox Code Playgroud)

它应该监听任何指定的通知,并在触发任何通知时进行处理.

但是这不会编译.我收到以下错误:

Value of type '[Observable<NSNotification>]' has no member 'merge'
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*vez 24

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

编辑: 或者作为RxSwift游乐场中的示例,您可以使用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)
Run Code Online (Sandbox Code Playgroud)