根据retryWhen() doc:
返回一个Observable,它发出与源相同的值 除了onError之外的observable。一个onError通知 从源头将导致Throwable项目的发射 Observable作为notificationHandler的参数提供 功能。如果Observable调用onComplete或onError,则重试 将在子订阅上调用onCompleted或onError。除此以外, 此Observable将重新订阅源Observable。
当count1值达到3时,将调用subscriber.onCompleted();在我的选项中,在调用subscriber.onCompleted()和" child_onCompleted&之后,将调用子订阅者的onComplete()方法。 #34;将出现在输出中,但它不是;为什么会发生这种情况?
count1 = 0;
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
System.out.println("call_onErr ");
subscriber.onError(new Throwable("gg!"));
}
}).retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> observable) {
System.out.println("fun_call+" + observable);
return observable.flatMap(new Func1<Throwable, Observable<?>>() {
@Override
public Observable<?> call(Throwable throwable) {
if (count1 < 3) {
count1 = count1 + 1;
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
System.out.println("fun_call_onNext " + " count=" + count1);
subscriber.onNext(1000);
}
});
} else
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
System.out.println("fun_call_onCompleted " + " " + count1);
subscriber.onCompleted();//this is the subscriber!!!!!!!
}
});
}
});
}
}).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("child_onCompleted ");
}
@Override
public void onError(Throwable e) {
System.out.println("child_err ");
}
@Override
public void onNext(Integer integer) {
System.out.println("child_onNext " + integer + " ");
}
});
输出是:
System.out﹕ fun_call+rx.Observable@3ecb7134
System.out﹕ call_onErr
System.out﹕ fun_call_onNext count=1
System.out﹕ call_onErr
System.out﹕ fun_call_onNext count=2
System.out﹕ call_onErr
System.out﹕ fun_call_onNext count=3
System.out﹕ call_onErr
System.out﹕ fun_call_onCompleted 3
答案 0 :(得分:0)
问题是你有flatMap,如果你发送一个空的Observable将无法完成。相反,您可以在其中使用特殊值并与takeWhile
运算符通信以触发完成:
Observable.error(new Throwable("gg!"))
.retryWhen(o -> {
AtomicInteger counter = new AtomicInteger();
return o.flatMap(e -> {
if (counter.getAndIncrement() < 3) {
return Observable.just(0);
}
return Observable.just(1);
})
.takeWhile(v -> v == 0);
})
.subscribe(...);