如何终止观测? [英] How to terminate an Observable?

查看:242
本文介绍了如何终止观测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可观察到的,我想终止如果某个条件没有得到满足(即,如果从某个网站的响应是不成功的),因此,我可以重新查询的网站,并再次调用观察到。我该如何去这样做?

这就是我想要做的:

  Observable.create(新Observable.OnSubscribe<串GT;(){
    @覆盖
    公共无效电话(订户LT ;?超级字符串>用户){        //此处执行网络行为        如果(!response.isSuccessful()){
            //终止本观测,所以我可以检索令牌,然后再次调用此观察到
        }
    }});


解决方案

您可以使用重试运营接收。并且不需要终止观察的。

定义自定义异常:

 公共类FailedException扩展RuntimeException的{
    // ...
}
私有静态最终诠释RETRY_COUNT = 3; //最大重试次数
Observable.create(新Observable.OnSubscribe<串GT;(){
        @覆盖
        公共无效电话(订户LT ;?超级字符串>用户){
            //此处执行网络行为
            如果(!response.isSuccessful()){
                //如果响应unsucceed,调用onError方法,它会停止发射数据,并进入重试方法。
                subscriber.onError(新FailedException());
            }
        }    })
    .retry((整数,抛出) - GT; {
        当失败重试//网络行为。
        //如果返回true,观测将重新尝试与网络操作发出的数据;
        订阅的//如果返回false,您可以在onError的处理()方法。
        返回抛出的instanceof FailedException&放大器;&安培;整数LT; RETRY_COUNT;
    })

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

});

解决方案

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

这篇关于如何终止观测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆