gpt4 book ai didi

android - RxJava 使 retryWhen() 触发 onError() 方法

转载 作者:搜寻专家 更新时间:2023-11-01 09:41:04 24 4
gpt4 key购买 nike

我有一个带有 RxJava 实现的以下类,用于从 API 下载两个资源。我做了一些 rx 以允许它在不满足 api/连接要求时重试或重复。但是,我无法让 retryWhen() 在尝试超过 3 次后触发 onError()。

问题/帮助

请检查我的代码并帮助我解决这个问题。

注意

我通过阅读这两篇文章来实现 Rx。 article 1 , article 2

SplashPresenter.class

public class SplashPresenter implements SplashContract.Presenter {

private static final String TAG = SplashPresenter.class.getName();
private static final int RETRY_TIMEOUT = 10;
private static final int STOP_RETRY_TIME = 3;
private static final int START_RETRY_TIME = 1;


private SplashContract.View mView;

@Override
public void init(SplashContract.View view) {
this.mView = view;
}

@Override
public void onResume() {

GetRemoteReceiverRelationshipSpec relationSpec = new GetRemoteReceiverRelationshipSpec();
GetRemoteIncompleteReasonSpec reasonSpec = new GetRemoteIncompleteReasonSpec();

Observable<RepoResult<ArrayList<IncompleteReasonViewModel>>> queryReason =
Repository.getInstance().query(reasonSpec);

Repository.getInstance().query(relationSpec)
.concatMap(result -> queryReason)
.repeatWhen(complete -> complete
.zipWith(Observable.range(START_RETRY_TIME, STOP_RETRY_TIME), (v, i) -> i)
.flatMap(repeatCount -> {
Log.i(TAG, "Repeat attempt: " + repeatCount);
mView.showLoadingDialog();
return Observable.timer(RETRY_TIMEOUT,
TimeUnit.SECONDS);
}))
.takeUntil(RepoResult::isSuccess)
.retryWhen(error -> error
.zipWith(Observable.range(START_RETRY_TIME, STOP_RETRY_TIME), (v, i) -> i)
.flatMap(retryCount -> {
Log.i(TAG, "Retry attempt: " + retryCount);
mView.showLoadingDialog();
if (mView.getCommunicator() != null) {
mView.getCommunicator().onConnectionFail(retryCount);
}
return Observable.timer(RETRY_TIMEOUT,
TimeUnit.SECONDS);
}))
.filter(RepoResult::isSuccess)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> Log.i(TAG, "onNext()"),
err -> {
Log.i(TAG, "onError()");
if (mView.getCommunicator() != null) {
mView.dismissLoadingDialog();
mView.getCommunicator().onSplashScreeDismissError();
}
},
() -> {
Log.i(TAG, "onComplete()");
if (mView.getCommunicator() != null) {
mView.dismissLoadingDialog();
mView.getCommunicator().onSplashScreenSuccessDismiss();
}
}
);
}

@Override
public void onPause() {

}
}

最佳答案

要在重试后保留 throwable(而不是发出自定义的),请在 retryCount 超过指定限制时从 zipWith 运算符返回一个带有适当错误的 Observable。

.retryWhen(error -> {
Observable<Integer> range = Observable.range(START_RETRY_TIME, STOP_RETRY_TIME);
Observable<Observable<Long>> zipWith = error.zipWith(range, (e, i) ->
i < STOP_RETRY_TIME ?
Observable.timer(i, TimeUnit.SECONDS) :
Observable.error(e));
return Observable.merge(zipWith);
});

关于android - RxJava 使 retryWhen() 触发 onError() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com