这是代码:
import io.reactivex.Observable;
import io.reactivex.Observer;
import org.junit.jupiter.api.Test;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
public class RxJavaTest {
@Test
public void onErr() {
Observable<String> values1 = new Observable<String>() {
@Override
protected void subscribeActual(Observer<? super String> observer) {
observer.onNext("New");
observer.onNext("New1");
observer.onNext("New2");
observer.onNext("New3");
observer.onNext("New4");
if (ThreadLocalRandom
.current()
.nextInt(10) == 5) {
observer.onError(new Exception("don't retry..."));
} else {
observer.onError(new IllegalArgumentException("retry..."));
}
}
};
AtomicBoolean finished = new AtomicBoolean(false);
values1
.retryWhen(throwableObservable -> throwableObservable
.takeWhile(throwable -> {
boolean result = (throwable instanceof IllegalArgumentException);
if (result) {
System.out.println("Retry on error: " + throwable);
return result;
}
System.out.println("Error: " + throwable);
return result;
})
.take(20))
.onErrorReturn(throwable -> "Saved the day!")
.doOnTerminate(() -> finished.set(true))
.subscribe(v -> System.out.println(v));
}
}
目标是
仅当存在IllegalArgumentException,
对于任何其他异常,立即返回(通过onErrorReturn)。
上面的代码实现了第一个目标,但第二个目标失败了,它停止重试,但忽略了该.onErrorReturn部分。
知道如何让它发挥作用吗?
慕盖茨4494581
慕田峪9158850
相关分类