'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 1:[1]

You can use merge to combine the two observables into a single observable. Then, do what @martin suggested and map each source's emissions to a little structure that allows you identify the source:

const obs1$: Observable<number[]> = getNumbers();
const obs2$: Observable<string[]> = getLetters();

const combined$ = merge(
  obs1$.pipe(map(data => ({ source: 'obs1$', data }))), 
  obs2$.pipe(map(data => ({ source: 'obs2$', data })))
);

combined$.subscribe(
   ({ source, data }) => console.log(`[${source}] data: ${data}`)
);

// OUTPUT:
//
// [obs1$] data: 1
// [obs2$] data: A
// [obs2$] data: A,B
// [obs2$] data: A,B,C
// [obs1$] data: 1,2
// [obs2$] data: A,B,C,D
...

Here's a little StackBlitz example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BizzyBob