rxjava:我可以使用 retry() 但有延迟吗? - rxjava: Can I use retry() but with delay?

问题:

I am using rxjava in my Android app to handle network requests asynchronously.我在我的 Android 应用程序中使用 rxjava 来异步处理网络请求。 Now I would like to retry a failed network request only after a certain time has passed.现在我想仅在经过一段时间后重试失败的网络请求。

Is there any way to use retry() on an Observable but to retry only after a certain delay?有什么方法可以在 Observable 上使用 retry() 但仅在一定延迟后重试?

Is there a way to let the Observable know that is is currently being retried (as opposed to tried for the first time)?有没有办法让 Observable 知道当前正在重试(而不是第一次尝试)?

I had a look at debounce()/throttleWithTimeout() but they seem to be doing something different.我查看了 debounce()/throttleWithTimeout() 但他们似乎在做一些不同的事情。

Edit:编辑:

I think I found one way to do it, but I'd be interested in either confirmation that this is the correct way to do it or for other, better ways.我想我找到了一种方法,但我对确认这是正确的方法或其他更好的方法感兴趣。

What I am doing is this: In the call() method of my Observable.OnSubscribe, before I call the Subscribers onError() method, I simply let the Thread sleep for the desired amount of time.我正在做的是:在我的 Observable.OnSubscribe 的 call() 方法中,在我调用 Subscribers onError() 方法之前,我只是让线程休眠所需的时间。 So, to retry every 1000 milliseconds, I do something like this:因此,要每 1000 毫秒重试一次,我会执行以下操作:

@Override
public void call(Subscriber<? super List<ProductNode>> subscriber) {
    try {
        Log.d(TAG, "trying to load all products with pid: " + pid);
        subscriber.onNext(productClient.getProductNodesForParentId(pid));
        subscriber.onCompleted();
    } catch (Exception e) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e.printStackTrace();
        }
        subscriber.onError(e);
    }
}

Since this method is running on an IO thread anyway it does not block the UI.由于此方法无论如何都在 IO 线程上运行,因此它不会阻塞 UI。 The only problem I can see is that even the first error is reported with delay so the delay is there even if there's no retry().我能看到的唯一问题是,即使是第一个错误也会延迟报告,因此即使没有 retry() 也会有延迟。 I'd like it better if the delay wasn't applied after an error but instead before a retry (but not before the first try, obviously).如果延迟不是错误之后应用而是重试之前(但显然不是在第一次尝试之前),我希望它会更好。


解决方案:

参考: https://stackoom.com/en/question/1UaUz
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章