Arno
Arno

Reputation: 101

Chain Observable RxJs in Angular

I use RxJs 6.6.0 and Angular 9.

I have two functions which returns Observable<'Class1'> and Observable<'number'>.

so I use to:

funcA().subscribe(x=>{ // do something...});

funcB().subscribe(x=>{// do somethings..});

But I need to call funcB only when funcA() is finish. I see than concat may be helpful but I can't get the two answers like that

concat(funcA,funcB).subscribe( (x,y)=>{// do with x
//do with y});

I would like to do this because parameters of funcB depend of the return of funcA.

Upvotes: 1

Views: 2109

Answers (2)

Rafi Henig
Rafi Henig

Reputation: 6414

Try implementing it in the following way:

import {  mergeMap } from 'rxjs/operators';

funcA()
  .pipe(
     mergeMap(valueFromA => {
         funcB({value: valueFromA }))
     }
   )
  .subscribe(console.log);

Upvotes: 2

Varit J Patel
Varit J Patel

Reputation: 3520

Use switchMap from rxjs/operators to achieve it.

this.sub = funcA()
  .pipe(
    switchMap(valueFromA => {
      // use valueFromA in here.
      return funcB()
    })
  )
  .subscribe();

Upvotes: 6

Related Questions