gpt4 book ai didi

rx-java - 可观察,仅在完成时重试错误和缓存

转载 作者:行者123 更新时间:2023-12-03 20:20:21 25 4
gpt4 key购买 nike

我们可以使用 cache() 运算符来避免多次执行长任务(http 请求),并重用其结果:

Observable apiCall = createApiCallObservable().cache(); // notice the .cache()

---------------------------------------------
// the first time we need it
apiCall.andSomeOtherStuff()
.subscribe(subscriberA);

---------------------------------------------
//in the future when we need it again
apiCall.andSomeDifferentStuff()
.subscribe(subscriberB);

第一次执行 http 请求,但第二次执行,因为我们使用了 缓存()运算符,请求将不会被执行,但我们将能够重用第一个结果。

当第一个请求成功完成时,这工作正常。但是如果 onError 在第一次尝试中被调用,那么下次新订阅者订阅同一个 observable 时,onError 将再次被调用,而不会再次尝试 http 请求。

我们试图做的是,如果第一次调用 onError ,那么下次有人订阅同一个 observable 时,将从头开始尝试 http 请求。即 observable 将只缓存成功的 api 调用,即调用 onCompleted 的那些调用。

关于如何进行的任何想法?我们尝试过使用 retry() 和 cache() 运算符,但运气不佳。

最佳答案

好吧,对于任何仍然感兴趣的人,我想我有一个更好的方法来实现它与 rx。

关键是使用 onErrorResumeNext,它可以让你在出现错误时替换 Observable。
所以它应该是这样的:

Observable<Object> apiCall = createApiCallObservable().cache(1);
//future call
apiCall.onErrorResumeNext(new Func1<Throwable, Observable<? extends Object>>() {
public Observable<? extends Object> call(Throwable throwable) {
return createApiCallObservable();
}
});

这样,如果第一次调用失败,以后的调用就会调用它(只有一次)。

但是每个其他尝试使用第一个 observable 的调用者都将失败并发出不同的请求。

你引用了原始的 observable,让我们更新它。

所以,一个懒惰的 setter/getter :
Observable<Object> apiCall;
private Observable<Object> getCachedApiCall() {
if ( apiCall == null){
apiCall = createApiCallObservable().cache(1);
}
return apiCall;
}

现在,如果前一个失败将重试的 setter/getter :
private Observable<Object> getRetryableCachedApiCall() {
return getCachedApiCall().onErrorResumeNext(new Func1<Throwable, Observable<? extends Object>>() {
public Observable<? extends Object> call(Throwable throwable) {
apiCall = null;
return getCachedApiCall();
}
});
}

请注意,每次调用它只会重试一次。

所以现在你的代码看起来像这样:
---------------------------------------------
// the first time we need it - this will be without a retry if you want..
getCachedApiCall().andSomeOtherStuff()
.subscribe(subscriberA);

---------------------------------------------
//in the future when we need it again - for any other call so we will have a retry
getRetryableCachedApiCall().andSomeDifferentStuff()
.subscribe(subscriberB);

关于rx-java - 可观察,仅在完成时重试错误和缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33195722/

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