I would like to know what is the best way using the RxJS library to execute 3 http requests that depends from the previous result.
Let's imagine that I've 3 services in my Angular application and each of them have a function get(id: number) use to subscribe an observable of the request entity.
I need to call sequencing the first service to get an entity which contains an identifier required for the next call by using the second service which also contains an identifier required for the next call using the third service.
Method 1: Using three subscriptions and set each result to global variables
const firstEntityId = 1;
this.firstService.get(firstEntityId)
.subscribe((firstEntity: FirstEntity) => {
this.firstEntity = firstEntity;
this.secondService.get(firstEntity.secondEntityId)
.subscribe((secondEntity: SecondEntity) => {
this.secondEntity = secondEntity;
this.thirdService.get(secondEntity.thirdEntityId)
.subscribe((thirdEntity: ThirdEntity) => {
this.thirdEntity = thirdEntity;
});
});
});
Method 2: Using function with stream and one subscription to set all global variables
const firstEntityId = 1;
this.getFirstSecondThird(firstEntityId)
.subscribe(([firstEntity, secondEntity, thirdEntity]: [FirstEntity, SecondEntity, ThirdEntity]) => {
this.firstEntity = firstEntity;
this.secondEntity = secondEntity;
this.thirdEntity = thirdEntity;
});
getFirstSecondThird(id: number): Observable<[FirstEntity, SecondEntity, ThirdEntity]> {
return this.firstService.get(id).pipe(
switchMap((firstEntity: FirstEntity) => forkJoin(
of(firstEntity),
this.secondService.get(firstEntity.secondEntityId)
)),
switchMap(([firstEntity, secondEntity]: [FirstEntity, SecondEntity]) => forkJoin(
of(firstEntity),
of(secondEntity),
this.thirdService.get(secondEntity.thirdEntityId)
))
);
}
In this case, does the method using stream is the fastest one ?
Is there an other way to write my function getFirstSecondThird instead of using switchMap and forkJoin methods ?
(I've seen combineLatest but I didn't found how to pass a parameter from the previous result)
combineLatest
is more appropriate when the calls are independent, but you need them to occur in sequence. The first method is more readable, what don't you like about it? – user8745435