RxJava2:有条件地重复/不在`repeatWhen`中重复
RxJava2: Repeat conditonally / don't repeat in `repeatWhen`
我有一个要定期重复的 Observable,但仅限于以下条件:
apiInterface.getData() // returns Observable<Data>
... // processing is happening here
.toList()
.repeatWhen(completed -> {
if (autoReload){
// Repeat every 3 seconds
return completed.delay(3, TimeUnit.SECONDS);
} else {
return ??? // What do I have to return that it does not repeat?
}
})
.subscribe(list -> callbackInterface.success(list));
我的问题是:我必须在 else
语句中 return 做什么才能不重复 Observable(只执行一次链)?
是Observable.empty()
。如 Javadoc 文档所述:
[..] If that Observable calls onComplete
or onError
then repeatWhen
will call onCompleted
or onError
on the child subscription. Otherwise, this Observable will resubscribe to the source observable.
所以完整的代码是:
apiInterface.getData() // returns Observable<Data>
... // processing is happening here
.toList()
.repeatWhen(completed -> {
if (autoReload){
// Repeat every 3 seconds
return completed.delay(3, TimeUnit.SECONDS);
} else {
return Observable.empty()
}
})
.subscribe(list -> callbackInterface.success(list));
您必须对完成指示器作出反应,以表示对某个项目的响应完成,例如:
completed.takeWhile(v -> false);
不幸的是,empty()
在那里不起作用,因为它会在源 运行.
之前立即完成序列
我有一个要定期重复的 Observable,但仅限于以下条件:
apiInterface.getData() // returns Observable<Data>
... // processing is happening here
.toList()
.repeatWhen(completed -> {
if (autoReload){
// Repeat every 3 seconds
return completed.delay(3, TimeUnit.SECONDS);
} else {
return ??? // What do I have to return that it does not repeat?
}
})
.subscribe(list -> callbackInterface.success(list));
我的问题是:我必须在 else
语句中 return 做什么才能不重复 Observable(只执行一次链)?
是Observable.empty()
。如 Javadoc 文档所述:
[..] If that Observable calls
onComplete
oronError
thenrepeatWhen
will callonCompleted
oronError
on the child subscription. Otherwise, this Observable will resubscribe to the source observable.
所以完整的代码是:
apiInterface.getData() // returns Observable<Data>
... // processing is happening here
.toList()
.repeatWhen(completed -> {
if (autoReload){
// Repeat every 3 seconds
return completed.delay(3, TimeUnit.SECONDS);
} else {
return Observable.empty()
}
})
.subscribe(list -> callbackInterface.success(list));
您必须对完成指示器作出反应,以表示对某个项目的响应完成,例如:
completed.takeWhile(v -> false);
不幸的是,empty()
在那里不起作用,因为它会在源 运行.