RxJava 操作符 take

[java]  view plain  copy
  1. Observable.interval(1, TimeUnit.SECONDS)  
  2.                   .take(10)  
  3.                   .subscribeOn(Schedulers.io())  
  4.                   .observeOn(AndroidSchedulers.mainThread())  
  5.                   .subscribe(new Subscriber<Long>() {  
  6.                     @Override public void onCompleted() {  
  7.                     }  
  8.   
  9.                     @Override public void onError(Throwable e) {  
  10.                     }  
  11.   
  12.                     @Override public void onNext(Long aLong) {  
  13.                     }  
  14.                   });  


take操作符和interval操作符联合使用,由于一旦interval计时开始除了解绑就无法停止,所以只有在onNext方法中计算一旦释放到10秒的时候再进行解绑从而终结该计时。但使用take操作符就简单很多了,它的意思是只释放前N项,和计时配合使用的话,就可以不用担心计时会一直执行,10秒过后它会自动结束。



[java]  view plain  copy
  1. /** 
  2.      * Returns an Observable that emits only the first {@code num} items emitted by the source Observable. 
  3.      * <p> 
  4.      * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.png" alt=""> 
  5.      * <p> 
  6.      * This method returns an Observable that will invoke a subscribing {@link Observer}'s 
  7.      * {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking 
  8.      * {@link Observer#onCompleted onCompleted}. 
  9.      * <dl> 
  10.      *  <dt><b>Scheduler:</b></dt> 
  11.      *  <dd>This version of {@code take} does not operate by default on a particular {@link Scheduler}.</dd> 
  12.      * </dl> 
  13.      *  
  14.      * @param num 
  15.      *            the maximum number of items to emit 
  16.      * @return an Observable that emits only the first {@code num} items emitted by the source Observable, or 
  17.      *         all of the items from the source Observable if that Observable emits fewer than {@code num} items 
  18.      * @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a> 
  19.      */  
  20.     public final Observable<T> take(final int num) {  
  21.         return lift(new OperatorTake<T>(num));  
  22.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值