RxSwift-如何具有可读的CombineLatest事件元素变量名称?

时间:2019-01-21 11:01:58

标签: ios swift rx-swift

var isCurrentlySearchingAddress = Variable<Bool>(false)
var currentSelectedPlace = Variable<GeocodePlace?>(nil)

我订阅时

Observable.combineLatest(viewModel.isCurrentlySearchingAddress.asObservable(), viewModel.currentSelectedPlace.asObservable())

我如何拥有可读的变量名,而不是01

enter image description here

3 个答案:

答案 0 :(得分:0)

如果您仅对next个事件感兴趣,可以这样做:

Observable.combineLatest(isCurrentlySearchingAddress.asObservable(), currentSelectedPlace.asObservable())
   .subscribe(onNext: { (isSearchingAddress, selectedPlace) in

   })

或者这个(如果您想继续使用subscribe):

Observable.combineLatest(isCurrentlySearchingAddress.asObservable(), currentSelectedPlace.asObservable())
   .subscribe { event in
      if case let .next(isSearchingAddress, selectedPlace) = event {

      }
   }

答案 1 :(得分:0)

您可以这样做:

    Observable.combineLatest(
        varA.asObservable(), varB.asObservable(),
        resultSelector: { value1, value2 in
            print("\(value1) \(value2)")
    }).observeOn(MainScheduler.instance)
        .subscribe()
        .disposed(by: disposeBag)

答案 2 :(得分:0)

在这里,您使用的是subscribe(on:),然后强制展开element。如果发生错误,elementnil发生故障,这将导致崩溃。强制将其拆开不是一个好主意。

如果您确定序列永远不会发出错误或不想处理错误,那么最好像这样使用subscribe(onNext:)

Observable.combineLatest(viewModel.isCurrentlySearchingAddress.asObservable(), viewModel.currentSelectedPlace.asObservable())
    .subscribe(onNext: { (isCurrentlySearchingAddress, currentSelectedPlace) in
    // Use isCurrentlySearchingAddress: Bool and currentSelectedPlace: GeocodePlace? here.
    if (isCurrentlySearchingAddress) {
        // TODO: 
    }
})

也不要忘记将其添加到DisposeBag