简体   繁体   中英

Why “Maybe.doOnDispose” is not supported in RxJava2?

I'm using Maybe class in RxJava2.

I registered the doOnDispose callback to detect the Dispose event, but it is not fired.

Maybe.just("aaa")
    .doOnDispose({ /* do something */ })
    .subscribe( ... )

I looked at the RxJava 2 code, but Maybe seemed not to support doOnDispose .

Maybe is create MaybePeek (not DoOnDisposeObserver ) object in doOnDispose ,,,

@CheckReturnValue
@SchedulerSupport("none")
public final Maybe<T> doOnDispose(Action onDispose) {
    return RxJavaPlugins.onAssembly(new MaybePeek(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, (Action)ObjectHelper.requireNonNull(onDispose, "onDispose is null")));
}

protected void subscribeActual(MaybeObserver<? super T> observer) {
    this.source.subscribe(new MaybePeek.MaybePeekObserver(observer, this));
}

But, Single is create DoOnDisposeObserver , and it is worked fine.

@CheckReturnValue
@SchedulerSupport("none")
public final Single<T> doOnDispose(Action onDispose) {
    ObjectHelper.requireNonNull(onDispose, "onDispose is null");
    return RxJavaPlugins.onAssembly(new SingleDoOnDispose(this, onDispose));
}

protected void subscribeActual(SingleObserver<? super T> s) {
    this.source.subscribe(new SingleDoOnDispose.DoOnDisposeObserver(s, this.onDispose));
}

Why Maybe.doOnDispose is not supported?

As the documentation says about doOnDispose(Action onDispose)

Calls the dispose Action if the downstream disposes the sequence.

Since your downstream never dispose it, it will never call.

Disposable disposable = Maybe.just("aaa")
    .doOnDispose({ /* do something */ })
    .subscribe( ... )

disposable.dispose();

Now the action in doOnDispose should be called.

Note that if the completion of the stream takes less time than the going to the next operation ( disposable.dispose() ), then the onDispose action should not be called. So, in order to verify it you can use a delay:

Disposable disposable = Maybe.just("aaa")
    .delay(2000, TimeUnit.MILLISECONDS)
    .doOnDispose({ /* do something */ })
    .subscribe( ... )

disposable.dispose();

Now the action should be fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM