我是rxjava的新手,我想每2秒执行一次轮询任务50次,如果某个条件在任务中遇到它也可能会终止,我正在尝试使用Observable.interval
但我发现有没有办法终止它除了抛出异常,是否还有其他运营商来实现我的目标?
BTW此功能作为API提供可观察对象,因此我无法通过取消描述来控制订阅者和终止。
Observable.interval(timeout, interval, TimeUnit.SECONDS)
.flatmap(task - > task)
答案 0 :(得分:18)
我猜Observable.takeUntil(stopPredicate)
或Observable.takeWhile(predicate)
可以帮助您:
Observable.interval(timeout, interval, TimeUnit.SECONDS)
.takeWhile(val -> val < 42)
此处可观察将在第42次尝试终止
答案 1 :(得分:2)
您可以使用Observable.interval
停止takeUntil
,如下所示:
Observable.interval(0, 1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.takeUntil(new Predicate<Long>() {
@Override
public boolean test(Long aLong) throws Exception {
return aLong == 10;
}
})
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
Log.d(TAG, "Tick: " + aLong);
}
});
在此示例中,10秒后,observable将停止。
答案 2 :(得分:1)
下面的代码将产生以下输出:
Starting interval..
Next tick is: 1
Next tick is: 2
Next tick is: 3
Next tick is: 4
Next tick is: 5
Interval complete
如果取消注释此行:“ // if(t == 3)dispose();”它只会打印以下内容:
Starting interval..
Next tick is: 1
Next tick is: 2
Next tick is: 3
代码:
Observable.interval(1, TimeUnit.SECONDS).take(5).subscribeWith(new DisposableObserver<Long>() {
@Override public void onStart() {
// do whatever might be needed here to run once before
// the interval begins
System.out.println("Starting interval..");
}
@Override public void onNext(Long t) {
System.out.println("Next tick is: "+t);
// if( t==3 ) dispose();
}
@Override public void onError(Throwable t) {
t.printStackTrace();
}
@Override public void onComplete() {
// will be called once when all 5 ticks are completed
// will NOT be called if dispose() has been called
System.out.println("Interval complete");
}
});