1

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Arno
  • 91
  • 2
  • 11

2 Answers2

6

Use switchMap from rxjs/operators to achieve it.

this.sub = funcA()
  .pipe(
    switchMap(valueFromA => {
      // use valueFromA in here.
      return funcB()
    })
  )
  .subscribe();
Varit J Patel
  • 3,497
  • 1
  • 13
  • 21
  • Why use `switchMap`? – Rafi Henig Aug 13 '20 at 13:27
  • Because: On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. – Varit J Patel Aug 13 '20 at 13:28
  • In case `mergeMap`, the inner subscription you have to manually control. By using `switchMap` it cancel automatically. That helps to avoid the memory leaks issue in case you forget to unsubscribe manually. [MergeMap Docs](https://www.learnrxjs.io/learn-rxjs/operators/transformation/mergemap) – Varit J Patel Aug 13 '20 at 13:33
  • @VaritJPatel valuefromA need to be assign to a filed of an object I give to funcB and not give directly the value. Remeber than FuncB return an observable – Arno Aug 13 '20 at 13:37
  • @RafiHenig I use the observer to get just one value from an api rest I develop – Arno Aug 13 '20 at 13:39
  • 1
    @Arno I showed you how you can use the value valuefromA to call funcB(). – Varit J Patel Aug 13 '20 at 13:41
  • @rafihenig - what do you mean with obsA will never emit again when you use switchMap..? I really don’t understand that statement.. – MikeOne Aug 13 '20 at 16:44
  • although in this case the `funcA` only emits once (http request) so there's no need for `switchMap` – Rafi Henig Aug 13 '20 at 17:13
2

Try implementing it in the following way:

import {  mergeMap } from 'rxjs/operators';

funcA()
  .pipe(
     mergeMap(valueFromA => {
         funcB({value: valueFromA }))
     }
   )
  .subscribe(console.log);
Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
  • I can't use the return of funcA and I need to asign this value to an object I give to funcB – Arno Aug 13 '20 at 13:34