我遇到了repeatWhen()
与Completable
合作的问题。以下代码块正在运行。订阅的Action
最终会在重复后运行。
completable
.subscribeOn(Schedulers.trampoline()) //for debug purposes; have also omitted completely
.repeat(2)
.observeOn(Schedulers.trampoline()) //for debug purposes; have also omitted completely
.subscribe(new Action() {
@Override
public void run() throws Exception {
//runs
}
}
但是,当我尝试以下
时completable
.subscribeOn(Schedulers.trampoline()) //for debug purposes; have also omitted completely
.repeatWhen(new MyRetry(2))
.observeOn(Schedulers.trampoline()) //for debug purposes; have also omitted completely
.subscribe(new Action() {
@Override
public void run() throws Exception {
//doesn't run
}
}
MyRetry
的定义如下:
class MyRetry implements Function<Flowable<Object>, Publisher<?>> {
private final int maxRetryCount;
private int retryCount;
/**
* @param maxRetryCount The number of times to repeat
*/
public MyRetry(final int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
retryCount = 0;
}
@Override
public Publisher<?> apply(final Flowable<Object> objectFlowable) throws Exception {
return objectFlowable.flatMap(new Function<Object, Publisher<?>>() {
@Override
public Publisher<?> apply(final Object o) throws Exception {
if (retryCount < maxRetryCount) {
retryCount++;
return Flowable.just(o);
} else {
return Flowable.empty();
}
}
});
}
}
订阅的Action
在完成重复后永远不会运行,但Completable
的原始订阅会重复两次。这让我相信我在返回Flowable.empty()
时可能不正确,但我无法找到有关此主题的信息,而且我对RxJava还不太新。我也有基础设施限制,让我仍然坚持使用Android中的Java 7。
答案 0 :(得分:1)
如果您在onCompleted()
课程中将flatMap()
更改为takeUntil()
,则初始订阅者将收到MyRetry
个活动:
@Override
public Publisher<?> apply(final Flowable<Object> objectFlowable) throws Exception {
return objectFlowable.takeWhile(o -> retryCount++ < maxRetryCount);
}
此问题已在this中讨论过 线程。