Easy implementation of Rxjava timer function

  • 2021-09-12 02:15:36
  • OfStack

Using RxJava to implement the timer function can be implemented in two ways, as follows:

1. Use the timer operator


private Disposable mDisposable;

 /**
  *  Start timer 
  */
 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();
     }
    });
 }


 /**
  *  Close the timer 
  */
 public void closeTimer(){
  if (mDisposable != null) {
   mDisposable.dispose();
  }
 }

2. Use the interval and take operators

In 1. x, timer can perform interval logic. In 2. x, this function is outdated and handed over to interval operator. Of course, only using interval can not realize timer function, so it must be combined with take operator. The specific code is as follows:


private Disposable mDisposable;

 /**
  *  Start timer 
  */
 public void startTime() {
  int count_time = 10; // Total time 
  Observable.interval(0, 1, TimeUnit.SECONDS)
    .take(count_time+1)// Set the total number of times to send 
    .map(new Function<Long, Long>() {
     @Override
     public Long apply(Long aLong) throws Exception {
      //aLong From 0 Begin 
      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();
     }
    });
 }

 /**
  *  Close the timer 
  */
 public void closeTimer(){
  if (mDisposable != null) {
   mDisposable.dispose();
  }
 }

Related articles: