Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift. CombineLatest. Not all observables emitted

Observable.combineLatest(...){...} contains several observables, but some of these observables were not emitted.

combineLatest emits only when all observables in this method were emitted.

How to skip not emitted observables and emit combineLatest?

let tap = firstButton.rx.tap.asObservable().map{ (_) -> Observable<Item> ...}

let textfieldObservable = viewTextField.rx.text.orEmpty.asObservable()

submitButton.rx.tap.withLatestFrom(Observable.combineLatest(textfieldObservable, tap ... )).flatMapLatest({
...
// this method will not be executed without tap on firstButton before tapping on submitButton

}
)
like image 558
Igor Kasuan Avatar asked Nov 20 '16 17:11

Igor Kasuan


Video Answer


1 Answers

combineLatest uses a closure that takes in as many arguments as it combines observables. So it makes sense it will wait for all the observables it combines to provide a value before it calls its closure.

But if you can find a sain default values for each of the observables provided to combineLatest, you could use startWith(_:) to force them into having an initial value.

This is what the code would look like using nil for item and the empty string for text

let tapObservable: Observable<Item> = // ...
let textField: Observable<String> = // ...

let combined = Observable.combineLatest(
  tapObservable.map { /* map everything to optional */ Optional.some($0) }.startWith(nil), 
  textField.startWith("")
) { item, text in
  // combine item and text
}

submitButton.rx.tap.withLatestFrom(combined)
like image 121
tomahh Avatar answered Nov 06 '22 17:11

tomahh