rxjs way of making a request from within a forkJoin that is dependant on one of the forkJoined requests

Viewed 81

I would like to make a request, that depends on another request, which is within a forkJoin. How do I make the request cleanly, without just calling it within the subscribe of the forkJoin?

Code looks a little bit like this right now: So the inner request in dependent on students in this case. I can't do it, before I don't have received my students from the backend.

forkJoin(
        this.service.requestNumber1(...),
        this.service.requestNumber2(...),
        this.service.requestNumber3(...)
      ).subscribe(res => {
        this.course = res[0];
        this.students = res[1];
        this.service.innerRequestIWantToReplace(this.students).subscribe(res => {
          this.iNeedStudentsForThis = .... ;
        });
        this.lessonLengthInMinutes = res[2];
      });
1 Answers

Why not just pipe the second request with the request you want to make like this:

forkJoin(
        this.service.requestNumber1(...),
        this.service.requestNumber2(...).pipe(mergeMap(res)=> this.service.innerRequestIWantToReplace(res)),
        this.service.requestNumber3(...)
      ).subscribe(res => {
        this.course = res[0];
        this.iDontNeedStudentsForThis = res[1];
        this.lessonLengthInMinutes = res[2];
      });

I piped it with mergeMap but you can use switchMap or a regular map too depending on your use case.

Related