RxJava 创建操作符 timer与interval

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

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

[java]  view plain  copy
  1. Observable.timer(5, TimeUnit.SECONDS).subscribe(new Observer() {  
  2.            @Override  
  3.            public void onCompleted() {  
  4.                LogUtils.d("------->onCompleted");  
  5.            }  
  6.   
  7.            @Override  
  8.            public void onError(Throwable e) {  
  9.   
  10.            }  
  11.   
  12.            @Override  
  13.            public void onNext(Long aLong) {  
  14.   
  15.            }  
  16.        });  

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

[java]  view plain  copy
  1. Observable.timer(0,5,TimeUnit.SECONDS).subscribe(new Subscriber() {  
  2.            @Override  
  3.            public void onCompleted() {  
  4.            }  
  5.   
  6.            @Override  
  7.            public void onError(Throwable e) {  
  8.   
  9.            }  
  10.   
  11.            @Override  
  12.            public void onNext(Long aLong) {  
  13.                LogUtils.d("------>along:"+aLong+" time:"+SystemClock.elapsedRealtime());  
  14.            }  
  15.        });  


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操作符:

[java]  view plain  copy
  1. Observable.interval(0,5,TimeUnit.SECONDS).subscribe(new Observer() {  
  2.             @Override  
  3.             public void onCompleted() {  
  4.   
  5.             }  
  6.   
  7.             @Override  
  8.             public void onError(Throwable e) {  
  9.   
  10.             }  
  11.   
  12.             @Override  
  13.             public void onNext(Long aLong) {  
  14.                 LogUtils.d("------>along:"+aLong+" time:"+SystemClock.elapsedRealtime());  
  15.             }  
  16.         });  
能达到同样的效果

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

你可能感兴趣的:(Android笔记,RxJava,interval,timer)