RxJava之倒计时

来源:互联网 发布:mac加密文件夹弹出 编辑:程序博客网 时间:2024/06/04 20:05

Android应用开发中经常用到倒计时的功能由好多种方式去实现如CountDownTimer,Handler&Timer&TimerTask或是原生控件Chronometer等,但是RxJava给了我们更好的选择。
RxJava1.x版本的实现是利用interval()与take()操作符结合实现的直接上代码:

public static Observable<Integer> countdown(int time) {
if (time < 0) time = 0;
final int count = time;
return Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.io())
.map(aLong -> count - aLong.intValue())
.take(count + 1);
}

使用方式:
xxx.countdown(count)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(value -> textView.setText(value.toString()));

相比CountDownTimer,Handler&Timer&TimerTask,很干净的代码了

重磅来了

昨天在RxJava的Github上阅读documentation/operators/range的时候发现在2.x版本下多了个API方法intervalRange就有类似的感觉 看了源码对方法的解释之后果然可以用来实现倒计时的功能
Observable intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler)
参数神马的大家应该很容易理解
官方注释:

Signals a range of long values, the first after some initial delay and the rest periodically after.
The sequence completes immediately after the last value (start + count - 1) has been reached.

代码来了–
Observable.intervalRange(start, count + 1, 0, 1000, TimeUnit.MILLISECONDS, Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> textView.setText(((count - aLong) + "")));

怎么样惊喜有木有?! 应该是最简单的实现倒计时功能的方法了吧 RxJava越来越有惊喜 大爱


彦神镇楼–
彦神镇楼图

原创粉丝点击