Angular - RxJS forkJoin and switchMap

forkJoin

forkJoin is used when you have a group of observables and only care about the final emitted value of each.

A good example of this is when you have multiple http get calls and wish to bundle up the results of all the http GET calls into a single array, which allows you to use array functions to manipulate the results easily.

const listOfObservables = someArray.map((element) => {
    return this.http.get(url);
}

//forkJoin accepts an array of observables
forkJoin(listOfObservables).subscribe((success) =>
    //success return an array of results from the observables
}

switchMap

switchMap is used when you want to use a result from an observable in another observable.

A good example of this is when you make a GET call to fetch some data and you wish to use that data to POST it to somewhere else.

it is better to use switchMap instead of 2 subscribes to avoid race conditions bugs

this.http.get(url).pipe(
    switchMap(response: any) => {
       const body = { response }
       return this.http.post(url, body);
    }
)