RxJava 创建操作符 timer与interval

timer操作符既可以延迟执行一段逻辑,也可以间隔执行一段逻辑,但是已经过时了,而是由interval操作符来间隔执行.

timer延迟执行例子:如延迟5秒:

 Observable.timer(5, TimeUnit.SECONDS).subscribe(new Observer() {
            @Override
            public void onCompleted() {
                LogUtils.d("------->onCompleted");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Long aLong) {

            }
        });

timer间隔执行:间隔5秒执行

 Observable.timer(0,5,TimeUnit.SECONDS).subscribe(new Subscriber() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Long aLong) {
                LogUtils.d("------>along:"+aLong+" time:"+SystemClock.elapsedRealtime());
            }
        });


02-19 17:27:35.683 25563-25987/com.rxandroid.test1 D/----->: ------>along:0 time:286032978
02-19 17:27:40.683 25563-25987/com.rxandroid.test1 D/----->: ------>along:1 time:286037976
02-19 17:27:45.683 25563-25987/com.rxandroid.test1 D/----->: ------>along:2 time:286042977
02-19 17:27:50.683 25563-25987/com.rxandroid.test1 D/----->: ------>along:3 time:286047976
02-19 17:27:55.683 25563-25987/com.rxandroid.test1 D/----->: ------>along:4 time:286052976


由于这种间隔执行已经标记为过时,推荐下面的方式:interval操作符:

Observable.interval(0,5,TimeUnit.SECONDS).subscribe(new Observer() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Long aLong) {
                LogUtils.d("------>along:"+aLong+" time:"+SystemClock.elapsedRealtime());
            }
        });
能达到同样的效果

注意timer与interval都是默认运行在一个新线程上面



你可能感兴趣的:(响应式编程)