Search code examples
angularrxjsrxjs6switchmap

How to use param from one stream in another with RX.js?


If I want to pass returned value from the first stream to second I use switchMap .

What should I use, if I want to use param from the first stream in second, but I don't want to do 2 subscribe?

this.firstStream$.subscribe(first => {
  this.secondStream$.subscribe(second => {
  // here I want to use first and second.
}

Solution

  • There's quite a few different ways to do it, depending what you are trying to accomplish. For example, there is ForkJoin:

    import { of, forkJoin} from 'rxjs';
    
    const firstObservable = of('David');
    const secondObservable = of('Acosta');
    
    forkJoin(firstObservable, secondObservable).subscribe(values => {
        const firstValue = values[0];
        const secondValue= values[1];
        console.log(firstValue);
        console.log(secondValue);
    });
    

    This waits for both to finish before emitting values. There are other operators you could use if you want one observable to emit first, such as switchMap, concat, etc.