Wujo
Wujo

Reputation: 1867

RxSwift - withLatestFrom combining values from both observables

I want to achieve result like this:

L -1-2-3------4------5-6-7-8----
R ---------A------B----------C--

O ---------A3-----B4---------C8

So basically something like withLatestFrom but combining values from both observables (like combine latest).

I guess there is no ready operator for that. Any idea how to achieve this?

Upvotes: 16

Views: 15943

Answers (4)

mmatiush
mmatiush

Reputation: 41

It looks like you can just swap R and L observables:

    R
       .withLatestFrom(L) { ($0, $1) }
       .subscribe(onNext: { r, l in
           print("\(r)\(l)")
       })

So the R will be the triggering observable and it will always take the last value from L

Upvotes: 0

milczi
milczi

Reputation: 7552

Short version where your R = input.r and L = input.l

let output = input.r
.withLatestFrom(input.l) { ($0, $1) }

Upvotes: 3

Caio Sym
Caio Sym

Reputation: 364

You can achieve this by using combineLatest with distinctUntilChanged followed by a map.

Observable.combineLatest(L,R) { lhs, rhs in
     return (lhs, rhs)
}
.distinctUntilChanged { last, new in 
     return last.1 != new.1
}
.map { combined in
     //Do your thing to create the combination
}

Upvotes: 2

Timofey Solonin
Timofey Solonin

Reputation: 1403

Just use resulting selector from your withLatestFrom. The overloaded implementation without closure simply ignores first observable. For example:

Observable.just("one")
  .withLatestFrom(Observable.just(1)) 
  { oneAsString, oneAsInt in return (oneAsString, oneAsInt) }

Upvotes: 24

Related Questions