如何在订阅/取消订阅时执行Completable

时间:2016-10-17 11:31:22

标签: java rx-java rx-android

有我的方法:

public void openWorkshift(WorkshiftSettings workshiftSettings, Subscriber<WorkshiftSettings> subscriber) {
    api.openWorkshift(workshiftSettings)
            .compose(RxOperatorsHelpers.additionalStacktrace())
            .doOnSubscribe(() -> actionsSystem.registerAction(...).await()) // <-
            .doOnUnsubscribe(() -> actionsSystem.unregisterAction(...).await()); // <-
            .subscribeOn(ioScheduler)
            .observeOn(uiScheduler)
            .doOnError(this::handleError)
            .subscribe(subscriber);
}

ActionsSystem.registerAction(...) / ActionsSystem.unregisterActions(...)看起来像这样:

public Completable registerAction(OperatorAction action) {
    return Completable.fromAction(() -> actions.add(action));
}

public Completable unregisterAction(OperatorAction action) {
    return Completable.fromAction(() -> actions.remove(action));
}

如您所见,我使用.await()在源Observable流中执行Completable。感觉就像错误的解决方案。 我怎样才能更优雅?

2 个答案:

答案 0 :(得分:1)

由于您Completable执行了一些简单的操作,您只需将代码内联到doOnSubscribedoOnUnsubscribe

        .doOnSubscribe(() -> actions.add(action))
        .doOnUnsubscribe(() -> actions.remove(action))

您可以从doOnSubscribe序列的其余部分开始andThen来避免Observable

actionsSyste.registerAction(...)
.andThen(api.openWorkshift(workshiftSettings)
        .compose(RxOperatorsHelpers.additionalStacktrace())
        .doOnUnsubscribe(() -> actionsSyste.unregisterAction(...).await())
        .subscribeOn(ioScheduler)
        .observeOn(uiScheduler)
        .doOnError(this::handleError)
 )
 .subscribe(...)

目前,当下游取消​​订阅时无法执行Completable,并且当序列正常终止或异常终止时,没有简单的方法来执行它。

答案 1 :(得分:1)

您可以使用Observable.defer。此运算符会延迟创建observable,直到订阅为止:

Observable observable = Observable.defer(() -> {
        actions.add(action);
        api.openWorkshift(workshiftSettings)
}).compose(RxOperatorsHelpers.additionalStacktrace())
    .subscribeOn(ioScheduler)
    .observeOn(uiScheduler)
    .doOnError(this::handleError);

然后使用Subscription。根据{{​​3}} Subscription.create()

  

创建并返回一个订阅,该订阅在取消订阅时调用给定的Action0。

所以基本上你需要这样做:

Subscription subscription = Subscriptions.create(new Action0() {
    @Override
    public void call() {
        actionsSyste.unregisterAction(...);
    }
});    
subscriber.add(subscription);
observable.subscribe(subscriber);