简体   繁体   English

重新执行一个可观察对象以通知当前订阅的观察者

[英]Re-execute an observable to notify currently subscribed observers

In an Android app scenario, I want to fetch some Observable<Data> from network, and there are multiple Observer<Data> subscribed to it to update corresponding views. 在一个Android应用程序场景中,我想从网络获取一些Observable<Data> ,并且有多个Observer<Data>订阅了它以更新相应的视图。 In case of error -say a timeout- show a button to the user to try again. 如果发生错误(例如超时),请向用户显示一个按钮以重试。

How can I do the try again part? 我该怎么做再试? can I tell the observable to re-execute its logic again without re-subscribing to it? 我可以告诉可观察对象重新执行其逻辑而不重新订阅吗?

Let's assume you have two buttons, "Retry" and "Cancel", initially hidden. 假设您有两个按钮“ Retry”和“ Cancel”,它们最初是隐藏的。 Create two Observable s retryButtonClicks and cancelButtonClicks . 创建两个ObservableretryButtonClickscancelButtonClicks Then, apply the retryWhen operator to the designated download flow and act upon the signals of these button clicks: 然后,将retryWhen运算符应用于指定的下载流,并根据以下按钮单击的信号进行操作:

download.retryWhen(errors -> {
    return errors
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap(e -> {
            // show the "Retry" and "Cancel" buttons around here
            return Observable.amb(
                    retryButtonClicks.take(1).map(v -> "Retry"),
                    cancelButtonClicks.take(1).map(v -> "Cancel")
                )
                .doOnNext(v -> { /* hide the "Retry" and "Cancel" buttons */ });
    })
    .takeWhile(v -> "Retry".equals(v))
    ;
});

There is actually specific methods 实际上有特定的方法

retry()

Returns an Observable that mirrors the source Observable, resubscribing to it if it calls onError (infinite retry count). 返回一个与源Observable镜像的Observable,如果它调用onError(无限重试计数),则重新订阅它。

and retry(long count) retry(long count)

Returns an Observable that mirrors the source Observable, resubscribing to it if it calls onError up to a specified number of retries. 返回一个与源Observable镜像的Observable,如果它调用onError直到指定的重试次数,则对其进行订阅。

Read more in an article and in the docs 文章文档中阅读更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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