RxJS Observable:在处理最后一个订阅时执行清理?

RxJS Observable: performing cleanup when the last subscription is disposed?

当 RxJS Observable 的 last subscription 被释放时,执行副作用的最干净的方法是什么?这可能发生在 Observable 终止之前

假设我需要一个返回 Observable 的函数,该函数会发出对资源的更改。我想在 所有订阅 都已处理后执行清理操作。

var observable = streamResourceChanges(resource);
var subscription1 = observable.subscribe(observer1);
var subscription2 = observable.subscribe(observer2);
// ...
subscription1.dispose();  // Does not perform the cleanup
subscription2.dispose();  // Performs the cleanup

我发现定义订阅处理操作的唯一方法是使用 Rx.Observable.create. The last disposal can be handled by sharing a subscription, for example with Observable.prototype.singleInstance().

例如:

function streamResourceChanges(resource) {
    return Rx.Observable.create(function(observer) {
        // Subscribe the observer for resource changes...
        // Return a cleanup function
        return function() {
            // Perform cleanup here...
            console.log("Cleanup performed!");
        };
    }).singleInstance();
}

是否有更简洁的方法来定义订阅处置的副作用,类似于 doOnNextdoOnCompleteddoOnError

var withCleanup = withoutCleanup.doOnDispose(function() {
    // Perform cleanup here...
});

根据您的实际用例,我想到了两个选择:

.finally()

source.finally(() => console.log("cleaning up")).singleInstance()

.using()

Rx.Observable
    .using(
        // allocate some disposable resource during subscribe.
        // resource.dispose() will be called during unsubscribe.
        () => new SomeResource(),

        // use the disposable resource to create your observable
        // for example...
        resource => Rx.Observable.interval(resource.time))
    .singleInstance();