gpt4 book ai didi

java - RxJava retry当重试整个方法时返回一个Completable

转载 作者:行者123 更新时间:2023-12-02 01:13:41 35 4
gpt4 key购买 nike

每次 API 响应无效 token 错误(重新身份验证)时,我都会尝试重新验证 token 。我有一个小例子,它复制了我面临的问题。基本上,第一次调用会抛出异常,这将触发重试,当重试时,auth方法不会再次完全调用(它不会打印“Entered Auth”,而是打印“authing...”)。

public class Example {

AtomicInteger atom = new AtomicInteger(1);

public Example(){}

public void start(){
auth().andThen(call())
.retryWhen(throwableFlowable -> throwableFlowable.flatMap(throwable -> {
System.out.println("Retrying...\n");
return Flowable.timer(1, TimeUnit.SECONDS);
}))
.subscribe(integer -> System.out.println("Result: " + integer), e -> System.out.println("Error" + e.getMessage()));
}

public Completable auth(){
System.out.println("Entered Auth");
return Completable.create(emitter -> {
System.out.println("authing...");
emitter.onComplete();
});
}

public Single<String> call(){
return getId()
.flatMap(this::getNameById);
}

public Single<Integer> getId(){
return Single.create(emitter -> {
emitter.onSuccess(atom.getAndIncrement());
});
}

public Single<String> getNameById(int id){
return Single.create(emitter -> {
HashMap<Integer, String> hash = new HashMap<>();
hash.put(1, "s");
hash.put(2, "b");
if(id == 1){
emitter.onError(new Throwable());
}else{
emitter.onSuccess(hash.get(id));
}
});
}

}

再次,这是我的输出:

Entered Auth
authing...
Retrying...

authing...
Result: b

如何强制整个 auth() 方法在重试时运行?

最佳答案

使用Completable.defer,它将包装您的 Completable 创建并在重试时重做,而不仅仅是重新订阅。

 Completable.defer(() -> auth()).andThen(call())
.retryWhen(throwableFlowable -> throwableFlowable.flatMap(throwable -> {
System.out.println("Retrying...\n");
return Flowable.timer(1, TimeUnit.SECONDS);
}))
.subscribe(integer -> System.out.println("Result: " + integer), e -> System.out.println("Error" + e.getMessage()));

输出:

Entered Auth
authing...
Retrying...

Entered Auth
authing...
Result: b

关于java - RxJava retry当重试整个方法时返回一个Completable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992043/

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