因为项目中有用到倒计时器,自己有时间的时候,用RxJava实现了一下Android中的倒计时功能。代码很简单,只是自己做着玩的。
代码实现:
public class CountdownUtils {
public static Observable<Integer> Countdown(int time){
if (time < 0) time = 0;
final int countTime = time;
return Observable.interval(0,1, TimeUnit.SECONDS)
.subscribeOn(AndroidSchedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(o ->{
return countTime - o.intValue();
}).take(countTime + 1);
}
}
使用方法:
CountdownUtils .Countdow(5).doOnUnsubscribe(() -> Log.d(TAG, "onCreate: ----"+"倒计时完成")) //这里是结束事件的时候会走这个方法
.subscribe(integer -> {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date(System.currentTimeMillis());
String s = formatter.format(date);
Log.d(TAG, "onCreate: ----当前时间"+s+"---"+integer); });
运行结果: