How to terminate an Observable?

强颜欢笑 提交于 2019-12-06 06:43:56

问题


I have an Observable that I want to terminate if a certain condition is not met (that is if the response from a certain website is unsuccessful), so that I can re-query the website, and call the observable again. How do I go about doing it?

Here's what I want to do:

Observable.create(new Observable.OnSubscribe<String>() {
    @Override
    public void call(Subscriber<? super String> subscriber) {

        //Perform network actions here

        if (!response.isSuccessful()) {
            //terminate this Observable so I can retrieve the token and call this observable again
        }
    }

});

回答1:


You can use the retry operator of Rx. And need not to terminate an Observable.

Defined a custom exception:

public class FailedException extends RuntimeException{
    // ...
}


private static final int RETRY_COUNT = 3; // max retry counts
Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            //Perform network actions here
            if (!response.isSuccessful()) {
                // if response is unsucceed, invoke onError method and it will be stop emit data and into retry method.
                subscriber.onError(new FailedException());
            }
        }

    })
    .retry((integer, throwable) -> {
        // Retry network actions when failed.
        // if return true, Observable will be retry to network actions emit data;
        // if return false, you can process in onError() method of Subscribe.
        return throwable instanceof FailedException && integer < RETRY_COUNT;
    })



回答2:


You can filter the result before subscribing. Do not handle it when you create your observable.

Check observable.filter function



来源:https://stackoverflow.com/questions/32989849/how-to-terminate-an-observable

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