【问题标题】:RxSwift Use withLatestFrom operator with multiple sourcesRxSwift 使用带有多个源的 withLatestFrom 运算符
【发布时间】:2020-06-18 14:15:11
【问题描述】:

我有 3 个 observables,即 source、source1 和 source2。我想要的是每当源发出不同的事件时获取源1和源2的值。这是我想出的代码,显然它不会编译,因为 withLatestFrom 只需要一个 observable。

source.distinctUntilChanged()
        .withLatestFrom(source1, source2) { ($0, $1.0, $1.1) }
        .subscribe(onNext: { (A, B, C) in
            print("OnNext called")
        })
        .disposed(by: bag)

【问题讨论】:

    标签: ios swift rx-swift reactive combine


    【解决方案1】:

    你几乎拥有它。将source1source2 结合起来怎么样?

    source.distinctUntilChanged()
        .withLatestFrom(Observable.combineLatest(source1, source2)) { ($0, $1.0, $1.1) }
        .subscribe(onNext: { (A, B, C) in
            print("OnNext called")
        })
        .disposed(by: bag)
    

    【讨论】:

      【解决方案2】:

      你可以这样做

              let source = PublishSubject<Int>()
              let source1 = PublishSubject<Int>()
              let source2 = PublishSubject<Int>()
      
              Observable
                  .combineLatest([source,source1,source2])
                  .distinctUntilChanged { (oldArray, newArray) -> Bool in
                      return oldArray.first == newArray.first
                  }
                  .subscribe(onNext: { (values) in
                      debugPrint("source1 value is \(values[1]) and source2 value is \(values[2])")
                  })
                  .disposed(by: self.disposeBag)
      
              source1.onNext(100)
              source2.onNext(200)
              source.onNext(3)
      
              source.onNext(4)
              source.onNext(4)
      

      O/P 看起来像

      赶上:

      我正在使用combineLatest,这意味着这只有在所有可观察对象至少发出一次值之后才会起作用。您始终可以使用 startWith 运算符来确保所有可观察对象至少发出一次值。

      【讨论】:

        猜你喜欢
        • 2020-09-09
        • 2021-04-09
        • 2018-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多