【问题标题】:Merging two notification observers in RxSwift在 RxSwift 中合并两个通知观察者
【发布时间】:2016-07-21 04:15:36
【问题描述】:

我有这段代码:

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'

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

【问题讨论】:

    标签: swift rx-swift reactivex


    【解决方案1】:

    .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)
    

    【讨论】:

    • 我想合并 2 种不同类型的观察者。知道如何实现吗?这就是我想要做的。 stackoverflow.com/questions/39050059/…
    • 你不能合并 2 种不同类型的 Observables。您必须转换其中一个或两者才能进行匹配!
    • @SwiftHipster 您可以使用zip 获取两个结果并手动合并
    • 如果可能,将它们映射到相同的类型,例如NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification).map({ _ in true}_
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2018-07-16
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多