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()
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).
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.
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 ...
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With