I am having trouble understanding the finalize operator in RxJS. Let me demonstrate this on an example:
of(null).pipe(
tap({ complete: () => console.log('tap 1 completes') }),
finalize(() => console.log('finalize')),
tap({ complete: () => console.log('tap 2 completes') })
).subscribe({ complete: () => console.log('subscribe completes') });
I would expect the finalize
callback to be executed before the second tap
. That's not happening, though. Rather the above code produces the following output:
tap 1 completes
tap 2 completes
subscribe completes
finalize
Looking at the implementation I believe the operator is passed (lifted) through the whole observable chain to always be applied at its end. So now I end up with two questions:
- What's the rationale behind this design decision? Can you give some explanation on why this is a desireable / advantageous property?
- Is there a different operator or other solution to execute code on complete and on error, but in order (i.e. before the second
tap
in the above example) rather than at the end of the observable chain?