Search code examples
javascripttypescriptrxjsobservable

How to combine 2 or more observables so that you know which emitted?


let's say you have 2 observables:

const obs1$: Observable<string[]> = this.getObs1$();
const obs2$: Observable<string[]> = this.getObs2$();

i want to combine these 2 so that in subscription (or rxjs map) i know which emitted the values. I can't use combineLatest because for the other observable i just get the latest value it emitted at some point.


Solution

  • There doesn't seem to be a purely RxJS solution to this (but hopefully someone can prove me wrong on that!)

    You could use a variable in the outter scope to track the emitting observable as a workaround

    let trigger: TriggerEnum;
    
    const obs1$: Observable<string[]> = this.getObs1$()
      .pipe(tap(() => trigger = TriggerEnum.One));
    const obs2$: Observable<string[]> = this.getObs2$()
      .pipe(tap(() => trigger = TriggerEnum.Two));;
    
    combineLatest(....).subscribe(
     // check trigger value
    );
    
    

    From the docs as a just-in-case: be aware that combineLatest will not emit an initial value until each observable emits at least one value