gpt4 book ai didi

java - retryWhen operator 从不重试

转载 作者:行者123 更新时间:2023-11-30 08:14:41 25 4
gpt4 key购买 nike

我正在通过重试实现数据库更新方法。遵循 retryWhen() 运算符的通用模式,如下所述:Using Rx Java retryWhen() ..

..但是我的重试逻辑从未执行过。我正在调试它,可以看到断点在下面显示的 place 3 命中,但它永远不会返回到 place 2 重试逻辑。在位置 3 之后,它总是会转到 位置 4,这是 onComplete 处理程序。

(代码使用 Java 8 lambdas)

I've applied a workaround by removing the retryWhen() block altogether and now invoking the updateWithRetrials() recursively from subscribe's > onError() block. That is working but I don't like that approach.

当我使用 retryWhen() 运算符时,请问有谁能提出错误的建议吗?

private void updateWithRetrials(some input x)

{

AtomicBoolean retryingUpdate = new AtomicBoolean(false);

...

// 1- Start from here
Observable.<JsonDocument> just(x).map(x1 -> {

if (retryingUpdate.get())
{
//2. retry logic
}

//doing sth with x1 here
...
return <some observable>;

})
.retryWhen(attempts -> attempts.flatMap(n -> {

Throwable cause = n.getThrowable();

if (cause instanceof <errors of interest>)
{
// 3 - break-point hits here

// retry update in 1 sec again
retryingUpdate.set(true);
return Observable.timer(1, TimeUnit.SECONDS);
}

// fail in all other cases...
return Observable.error(n.getThrowable());
}))
.subscribe(
doc -> {
//.. update was successful
},

onError -> {
//for unhandled errors in retryWhen() block
},

{
// 4. onComplete block

Sysout("Update() call completed.");
}

); //subscribe ends here

}

最佳答案

您的问题是由于 Observable.just() 的一些性能优化所致。

此 Operator 在发出项目后,不会检查订阅是否未取消,并在所有情况下发送 onComplete。

Observable.retryWhen(并重试)重新订阅错误,但在源发送 onComplete 时终止。

因此,即使重试运算符重新订阅,它也会从之前的订阅获得 onComplete 并停止。

您可能会看到,下面的代码失败了(和您的一样):

@Test
public void testJustAndRetry() throws Exception {
AtomicBoolean throwException = new AtomicBoolean(true);
int value = Observable.just(1).map(v->{
if( throwException.compareAndSet(true, false) ){
throw new RuntimeException();
}
return v;
}).retry(1).toBlocking().single();
}

但是如果你“不要忘记”检查订阅,它就可以工作!:

@Test
public void testCustomJust() throws Exception {
AtomicBoolean throwException = new AtomicBoolean(true);
int value = Observable.create((Subscriber<? super Integer> s) -> {
s.onNext(1);
if (!s.isUnsubscribed()) {
s.onCompleted();
}
}
).map(v -> {
if (throwException.compareAndSet(true, false)) {
throw new RuntimeException();
}
return v;
}).retry(1).toBlocking().single();

Assert.assertEquals(1, value);
}

关于java - retryWhen operator 从不重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324886/

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