rxjs - Angular: How to wait for an Observable function, to call another function that returns an Observable?

Viewed 927

I have 2 API calls in a service that each return an Observable, and in my component I have some condition that, if true, I must call both those functions, but I need to wait for the get() call, so that I can execute the post function with arguments returned from the get call. If false, I just want to call the post function with the already defined arguments.

service:

  get(id: string) {
    return this.http.get<any>('get path');
  }

  post(data: data) {
    return this.http.post<any>('post path', {data: data});
  }

component:

  execute() {
    if (condition) {
      this.service.get(id).subscribe( (res) =>
        // ...
        this.data = res.data;
        post(data).subscribe(() => // do stuff...);
      );
    } else { post(data).subscribe(() => // do stuff...); }
   }

I want to not repeat code for the post call, or if not at all possible, just not use a subscribe() inside another subscribe(). How can I do this? without async await.

Thanks in advance

2 Answers

You could use RxJS switchMap operator to map from one observable to another (in your case GET to POST) and use RxJS iif function to conditionally return an observable.

Try the following

execute() {
  const getPost$ = this.service.get(id).pipe(
    switchMap((res: any) => {
      this.data = res.data;
      return this.service.post(data);
    })
  );


  iif(
    () => condition,
    getPost$,
    this.service.post(data)
  ).subscribe(
    (res: any) => { 
      // handle response
    },
    (error: any) => {
      // handle error
    }
  );
}

Another solution could look like the following:

const source$ = condition
  ? this.service.get(id) // Get new data
  : of(this.data); // Use already defined data

source$.pipe(
  concatMap(data => this.service.post(data)), 
)
Related