美文网首页
Android RxJava 创建操作符Timer

Android RxJava 创建操作符Timer

作者: Angelicas | 来源:发表于2017-06-09 10:33 被阅读708次

    之前有写过Android实现倒计时之使用CountDownTimer,除了CountDownTimer,开发中我们也会用到handler,例如

     mHandler.sendEmptyMessageDelayed(1, 10*1000);
        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.e("流程", "10秒时间已到");
            }
        };
    

    现在结合RxJava来的Observable.timer操作符,既可以延迟执行一段逻辑,也可以间隔执行一段逻辑
    (1)Timer 延迟10秒执行:

    private void timer() {
            Observable.timer(10000, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            Log.e("流程", "10秒倒计时已结束");
                        }
                    });
        }
    

    (2)Timer 间隔1秒执行:

     private Subscription subscribe;
        private void timer() {
            subscribe= Observable.timer(1000,1000,TimeUnit.MILLISECONDS).subscribe(new Subscriber<Long>() {
                @Override
                public void onCompleted() {
                }
    
                @Override
                public void onError(Throwable e) {
    
                }
    
                @Override
                public void onNext(Long aLong) {
                    Log.e(TAG, "------>along:"+aLong+" time:"+ SystemClock.elapsedRealtime());
                }
            });
        }
    

    记得要取消订阅

      private void stop() {
            if (subscribe != null && !subscribe.isUnsubscribed()) {
                subscribe.unsubscribe();
            }
        }
    

    相关文章

      网友评论

          本文标题:Android RxJava 创建操作符Timer

          本文链接:https://www.haomeiwen.com/subject/dimtqxtx.html