There may not be much more to add to this discussion.
It is worth noting that the EMPTY
in RxJs is a stream that emits nothing and completes immediately. It can be likened to a "break" statement, though the manner in which you "break" from a stream can vary depending on the context.
this.service.create('/api/employee').pipe(
catchError(err1 => {
// perform some actions
return throwError(err1);
}),
switchMap(resp1 => {
// carry out some operations
if(someCondition(resp1)){
return this.service.update('/api/salary/', id).pipe(
catchError(err2 => {
// perform some actions
return throwError(err2);
}),
);
}
return EMPTY;
}),
switchMap(resp2 => {
// perform some actions
if(someCondition(resp2)){
return this.service.delete('/api/education/', id).pipe(
catchError(err3 => {
// perform some actions
return throwError(err3);
}),
);
}
return EMPTY;
}),
).subscribe({
next: resp3 => { /*perform some actions*/ },
complete: () => { /*Your stream has concluded*/ },
eror: err => { /*All re-thrown errors are caught here */ }
});
Update
Utilizing tap
to gain insight into streams
tap
is an operator that mirrors the stream it receives without making any alterations. It can be used to observe the behavior of a stream at various points, aiding in comprehension.
http1().pipe(
tap({
next: val => console.log("Result from http1 call: ", val),
complete: () => console.log("http1 call completed"),
error: err => console.log("http1 call errored: ", err)
})
switchMap(val => http2(val).pipe(
tap({
next: val => console.log("Result from http2 call: ", val),
complete: () => console.log("http2 completed"),
error: err => console.log("http2 call errored: ", err)
})
)),
tap({
next: val => console.log("Result from switchMap operator: ", val),
complete: () => console.log("switchMap completed"),
error: err => console.log("switchMap (http1 or http2 call) errored: ", err)
})
).subscribe()
This example illustrates the actions taken before and after the switchMap
operator. It is evident that in this scenario, switchMap receives a value from http1 and emits values from http2.
Due to the fact that switchMap waits for values from http1 before triggering http2, a consequence is that http2 only starts after http1 emits. This sequential execution is altered if http1 emits multiple times.
Further Reading: