You have more options, there are some *map
operators, that handle the flow differently. By your example you could use switchMap, which cancels your running observable (in your example the getAnother
).
There's a Operator Decision Tree in the docs, try it, it can help a lot.
You get switchMap
with this logic:
- I have one existing Observable, and
- I want to start a new Observable for each value
- and cancel the previous nested Observable when a new value arrives
- where the nested Observable is calculated for each value
One other note, you should have your takeUntil
to be placed last.
You could write something like this:
getSth(): void {
this.service.functionName.pipe(
// If service.functionName returns a new object every time distinctUntilChanged will do nothing as references won't be the same.
// distinctUntilChanged(),
switchMap(resp => this.anotherService.anotherFunctionName(resp.event))
takeUntil(this.destroy$),
).subscribe((result) => {
this.result = result;
}));
}