我的代码是这样的:
输出结果为:
It just come in
number is: 6
Boo!
我的期望是如果异常是FooException,它应该重新订阅,但是,它看起来只是订阅一次。
我不知道我的代码有什么问题。
还有一个问题,如何设置最大重试次数(例如,甚至返回FooException,我只想重新订阅两次)
public class ErrorEmitter implements Observable.OnSubscribe<Integer> {
private int throwAnErrorCounter = 7;
public void call(Subscriber<? super Integer> subscriber) {
System.out.println("It just come in");
if (throwAnErrorCounter > 4) {
throwAnErrorCounter--;
System.out.println("number is: "+throwAnErrorCounter);
subscriber.onError(new FooException());
return;
}
if (throwAnErrorCounter > 0) {
throwAnErrorCounter--;
System.out.println("number is: "+throwAnErrorCounter);
subscriber.onError(new BooException());
return;
}
System.out.println("number is will complete");
subscriber.onCompleted();
}
}
Observable.create(new ErrorEmitter()).retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
public Observable<?> call(Observable<? extends Throwable> attempts) {
return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
public Observable<?> call(Throwable error) {
if (error instanceof FooException) {
return Observable.timer(1L, TimeUnit.SECONDS);
}
return Observable.error(error);
}
}
);
}
}).subscribe(new Subscriber<Integer>() {
public void onCompleted() {
System.out.println("complete");
}
public void onError(Throwable throwable) {
System.out.println(throwable.getMessage());
}
public void onNext(Integer integer) {
System.out.println("it is in next ");
}
});
答案 0 :(得分:1)
您的代码没有任何问题。尝试将timer
替换为Observable.just(null)
,看看是否可以找出问题所在。