我有这段代码:
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)
关于swift - 在 RxSwift 中合并两个通知观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36354927/