I am facing an issue where I need to make multiple server calls to save data, with each subsequent call requiring some data from the result of the previous call. I attempted to use forkJoin but encountered a problem with the sequence of events not making sense to me. It seems like the issue lies in the .pipe() call where I am attempting to modify the input data for the next call.
This situation raises two main questions:
- Why is the output not aligning with my expectations?
- Is there a way to resolve this using forkJoin? (I acknowledge that there are alternative approaches to solving this problem, but I am specifically interested in making forkJoin work in this scenario)
Below is a snippet of the code, or you can view it on StackBlitz.
let data: { [key: string]: any } = {};
forkJoin(
this.saveFirst(data).pipe(
tap(_ => console.log('saveFirst pipe after')),
tap(result => data.id = result.id)
),
this.saveSecond(data).pipe(
tap(_ => console.log('saveSecond pipe after')),
tap(result => data.name = result.name)
),
).subscribe(result => console.log('done: data - ', JSON.stringify(data)));
...
private saveFirst(data: { [key: string]: any }): Observable<any> {
console.log('saveFirst: start');
console.log('saveFirst: data - ', JSON.stringify(data));
return of({ id: 1 }).pipe(tap(_ => console.log('saveFirst: end')));
}
private saveSecond(data: { [key: string]: any }): Observable<any> {
console.log('saveSecond: start');
console.log('saveSecond: data - ', JSON.stringify(data));
return of({ name: 'test' }).pipe(tap(_ => console.log('saveSecond: end')));;
}
I was anticipating the following output:
saveFirst: start
saveFirst: data - {}
saveFirst: end
saveFirst pipe after
saveSecond: start
saveSecond: data - {}
saveSecond: end
saveSecond pipe after
done: data - {"id":1,"name":"test"}
However, the actual output I received was:
saveFirst: start
saveFirst: data - {}
saveSecond: start
saveSecond: data - {}
saveFirst: end
saveFirst pipe after
saveSecond: end
saveSecond pipe after
done: data - {"id":1,"name":"test"}