简体   繁体   中英

RxSwift - how to have readable combineLatest event element variable names?

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

when I make a subscription on

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

How can I have readable variable names instead of 0 and 1 ?

在此处输入图片说明

If you are only interested in next events you can do this:

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

   })

Or this (if you want to keep using subscribe ):

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

      }
   }

You can do it like this:

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

Here you're using the subscribe(on:) then force unwrapping element . In case of error the element will we nil and it will cause crash. It is not a good idea to force unwrap it.

If you're sure that the sequence will never emit error or you don't want to handle the error then it's better to use subscribe(onNext:) like this:

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

Also don't forget to add it to DisposeBag .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM