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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章