How to terminate an Observable?

2019-04-10 04:21发布

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
        }
    }

});

2条回答
啃猪蹄的小仙女
2楼-- · 2019-04-10 04:52

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;
    })
查看更多
Explosion°爆炸
3楼-- · 2019-04-10 05:15

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

Check observable.filter function

查看更多
登录 后发表回答