TL;DR:
Assuming a function teardown()
that holds your teardown logic an original: Observable
that you need to enhance:
new Observable(
sub => original.subscribe(sub).add(() => teardown())
)
A simple, fool-proof one-liner
This section merely explains the code in the TL;DR: above.
There actually is a way:
Simply create a new Observable
with your additional TeardownLogic
and let its subscriptions actually subscribe to your original
one!
const original: Observable<T> = // [...]
return new Observable(subscription => {
// Add custom teardown logic
subscription.add(() => teardown());
// Delegate to the original `Observable`
original.subscribe(subscription);
});
You may also simply provide the TeardownLogic
callback as a result of the subscription handler you pass to the constructor of the new Observable
:
const original: Observable<T> = // [...]
return new Observable(subscription => {
// Delegate to the original `Observable`
original.subscribe(subscription);
// Define the teardown logic here
return () => teardown();
});
Also
Don't hesitate to actually inline the original
Observable
if you may!
new Observable(
sub => fromEvent(document, 'click').subscribe(sub).add(() => teardown())
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// your `original` Observable
)