Observable.interval(1, TimeUnit.SECONDS)
.take(10)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Long>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
}
@Override public void onNext(Long aLong) {
}
});
take操作符和interval操作符联合使用,由于一旦interval计时开始除了解绑就无法停止,所以只有在onNext方法中计算一旦释放到10秒的时候再进行解绑从而终结该计时。但使用take操作符就简单很多了,它的意思是只释放前N项,和计时配合使用的话,就可以不用担心计时会一直执行,10秒过后它会自动结束。
/**
* Returns an Observable that emits only the first {@code num} items emitted by the source Observable.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.png" alt="">
* <p>
* This method returns an Observable that will invoke a subscribing {@link Observer}'s
* {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking
* {@link Observer#onCompleted onCompleted}.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code take} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param num
* the maximum number of items to emit
* @return an Observable that emits only the first {@code num} items emitted by the source Observable, or
* all of the items from the source Observable if that Observable emits fewer than {@code num} items
* @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a>
*/
public final Observable<T> take(final int num) {
return lift(new OperatorTake<T>(num));
}