使用RxJava實(shí)現(xiàn)定時(shí)器功能可以通過兩種方式來實(shí)現(xiàn),具體實(shí)現(xiàn)如下:
一、使用 timer 操作符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
private Disposable mDisposable; /** * 啟動(dòng)定時(shí)器 */ public void startTime() { Observable.timer( 10 , TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Observer<Long>() { @Override public void onSubscribe(Disposable d) { mDisposable = d; } @Override public void onNext(Long value) { //Log.d("Timer",""+value); } @Override public void onError(Throwable e) { } @Override public void onComplete() { // TODO:2017/12/1 closeTimer(); } }); } /** * 關(guān)閉定時(shí)器 */ public void closeTimer(){ if (mDisposable != null ) { mDisposable.dispose(); } } |
二、使用使用 interval 和 take 操作符
在1.x 中 timer 可以執(zhí)行間隔邏輯,在2.x中此功能已過時(shí),交給了 interval 操作符,當(dāng)然只使用 interval 還不能實(shí)現(xiàn)定時(shí)器功能,必須再結(jié)合take 操作符。具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
private Disposable mDisposable; /** * 啟動(dòng)定時(shí)器 */ public void startTime() { int count_time = 10 ; //總時(shí)間 Observable.interval( 0 , 1 , TimeUnit.SECONDS) .take(count_time+ 1 ) //設(shè)置總共發(fā)送的次數(shù) .map( new Function<Long, Long>() { @Override public Long apply(Long aLong) throws Exception { //aLong從0開始 return count_time-aLong; } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Observer<Long>() { @Override public void onSubscribe(Disposable d) { mDisposable = d; } @Override public void onNext(Long value) { //Log.d("Timer",""+value); } @Override public void onError(Throwable e) { } @Override public void onComplete() { // TODO:2017/12/1 closeTimer(); } }); } /** * 關(guān)閉定時(shí)器 */ public void closeTimer(){ if (mDisposable != null ) { mDisposable.dispose(); } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/MillerKevin/article/details/78890375