Josef.B Josef.B - 2 months ago 8x
Javascript Question

How to add action function to Disposable returned from subscribe on an Observable?

You have an Observable, then you subscribe to it. The return value is a Disposable. How do you add a function to be invoked when that Disposable instance is disposed?


When dispose() is invoked I want to call a debug function, for example, console.log('Disposing ....'). In a real app, I would want to do some non-rxjs clean-up and UI notification actions. Probably simple thing, but I don't see it in the API. Thx.


I wonder if finally would work for your use case (documentation). According to the documentation, Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. Note that this is not exactly the same as a callback being called when dispose is called but I thought that might be enough for your needs, and you can use it for clean-up actions.


Also close to what you want, but not quite so, you could use the using operator (documentation). It allows to create an object with a dispose method which would be called when the subscription to the associated observable is disposed of.


Looking at the source code, finally actually executes the action when the subscription to its observable is disposed. This includes termination or manually calling dispose() on the subscription. That seems very close to what you want to achieve.

Best is to test. Please keep us updated of the results.