How to properly stop rxjava Flowable?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 19:14:32

问题


I have the following code structure

Service

public Flowable entryFlow()
{
    return Flowable.fromIterable(this::getEntries)
}

Consumer

void start()
{
    disposable = service
        .entryFlow()
        .observeOn(Schedulers.computation())
        .subscribeOn(Schedulers.computation())
        .subscribe(
            entry -> ...,
            this::onError,
            this::subscriptionFinished);
}

void stop()
{
    disposable.dispose();
}

private void onError(Throwable e)
{
    subscriptionFinished();
}

private void subscriptionFinished()
{
    //
}

I need a way to stop the flowable from fetching and emitting data when the stop method is called.

By doing the following, I noticed that the doOnCancel lambda is not always called.

void start()
{
    disposable = service
        .entryFlow()
        .observeOn(Schedulers.computation())
        .subscribeOn(Schedulers.computation())
        .doOnCancel(this::snapshotFinished)
        .subscribe(
            entry -> ...,
            this::onError,
            this::subscriptionFinished);
}

void stop()
{
    disposable.dispose();
}

Alternative would be

volatile stopped;

void start()
{
    disposable = service
        .entryFlow()
        .observeOn(Schedulers.computation())
        .subscribeOn(Schedulers.computation())
        .takeUntil(x -> stopped)
        .subscribe(
            entry -> ...,
            this::onError,
            this::subscriptionFinished);
}

void stop()
{
    stopped = true;
}

What would be the recommended implementation of start and stop such that the flowable stops emitting and onComplete or a similar method (doOnCancel action?) is called?

Later Edit:

To make my use-case shorter

Is is enough to call disposable.dispose to stop the flowable getting data from iterable and emitting to source? I only have 1 subscriber and need to have either onComplete/onError/other-callback called when the flowable ends regardless of cause.

By other callback I mean one of doOnCancel/doFinally etc.

Thank you


回答1:


I would recommend to use the dispose() method. And then just add doOnDispose to trigger your side-effect-code.



来源:https://stackoverflow.com/questions/48754154/how-to-properly-stop-rxjava-flowable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!