Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what triggered combineLatest?

I have a few observables. And I need to know which one triggered the subscribe.

Observable.combineLatest(
      this.tournamentsService.getUpcoming(),
      this.favoriteService.getFavoriteTournaments(),
      this.teamsService.getTeamRanking(),
(tournament, favorite, team) => {
//what triggered combinelatest to run?
}).subscribe()
like image 219
AlexZvl Avatar asked Nov 25 '16 12:11

AlexZvl


People also ask

What is the use of combineLatest?

combineLatest allows to merge several streams by taking the most recent value from each input observable and emitting those values to the observer as a combined output (usually as an array).

What is the difference between forkJoin and combineLatest?

The combineLatest operator enforces a source Observable to start emitting only when all the inner Observables emit at least once. The forkJoin operator enforces a source Observable to start emitting only when all the inner Observables are complete.

What is the difference between ZIP and combineLatest?

The CombineLatest operator behaves in a similar way to Zip, but while Zip emits items only when each of the zipped source Observables have emitted a previously unzipped item, CombineLatest emits an item whenever any of the source Observables emits an item (so long as each of the source Observables has emitted at least ...

What is combineLatest in Rxjava?

combineLatest() factory is somewhat similar to zip() , but for every emission that fires from one of the sources, it will immediately couple up with the latest emission from every other source. It will not queue up unpaired emissions for each source, but rather cache and pair the latest one.


1 Answers

A quite clean and "rx"-way of achieving this is by using the timestamp operator http://reactivex.io/documentation/operators/timestamp.html

Example code

sourceObservable
  .pipe(
    timestamp(),  // wraps the source items in object with timestamp of emit
    combineLatest( otherObservable.pipe( timestamp() ), function( source, other ) {

      if( source.timestamp > other.timestamp ) {

        // source emitted and triggered combineLatest
        return source.value;
      }
      else {

        // other emitted and triggered combineLatest
        return other.value;
      }

    } ),
  )

If more than two observables are involved in the combineLatest() sorting them by timestamp would enable to detect which one triggered the combineLatest().

like image 58
steinharts Avatar answered Sep 20 '22 04:09

steinharts