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

时间:2015-10-26 19:19:00

标签: javascript rxjs reactive-extensions-js

在处理RxJS Observable的最后订阅时,执行副作用的最简洁方法是什么?这可能会在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。最后一次处理可以通过共享订阅来处理,例如使用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...
});

1 个答案:

答案 0 :(得分:13)

根据您的实际使用情况,我会想到两个选择:

.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();