Dispose of a resource asynchronously in the unsubscribe function

Viewed 405

I want to asynchronously dispose of a resource in the unsubscribe function of an observable. For example:

// rxjs 6
let observable = Observable.create(sub => {
    let resource = new Resource();
    return {
        async unsubscribe() {
            await resource.dispose();
        }
    }

};

The problem is that because the unsubscribe function isn't supposed to return a Promise, nothing will await it so the unsubscribe function will be "over early", before the resource is fully disposed of. This can cause behavior that shouldn't happen while the resource is being disposed of.

How do I deal with this?

1 Answers

There is no hint in the RxJS source code that the result of Subscription.unsubscribe could be used for awaiting asynchronous code executions.

We see unsubscribe may return an errorObject that would be cought and treated, but it isn't returned by the unsubscribe function to the consumer itself, so there's no chance on waiting for that.

It also seems to be implemented this way by design. The Observable contract states:

When an observer issues an Unsubscribe notification to an Observable, the Observable will attempt to stop issuing notifications to the observer. It is not guaranteed, however, that the Observable will issue no notifications to the observer after an observer issues it an Unsubscribe notification.

This suggests, that the unsubscribe notification is not supposed to guarentee the completeness of the Observable in any way.

Alternatively, the complete notification seems to be what we are looking for. Semantically, it seems to fit the requirement, as it indicates that the Observable has reached its final lifecycle state.

EDIT

After trying out my previous approach I noticed that the complete notification wouldn't reach the subscriber after unsubscribe was used, so that's also not an option. I think there is no solution for the requirement at this point.

Related