Android Retrofit2实现倒计时
2020-08-20 本文已影响0人
可乐_JS
-
记录一次使用Retrofit2实现倒计时功能
1.在需要的module中添加依赖
implementation "io.reactivex.rxjava2:rxjava:2.1.0"
2.代码实现
/**
* Des: 倒计时
* Created by kele on 2020/7/17.
* E-mail:984127585@qq.com
*/
public class RX2CountDownTimer {
private Disposable disposable;
private RX2CountDownTimer() {
}
public static RX2CountDownTimer getInstance() {
return new RX2CountDownTimer();
}
public interface RX2CountDownTimerCallback {
void onNext(boolean isFinish, long time);
}
/**
* 开始倒计时
*
* @param allSecTimes 倒计时总时长 单位:秒
* @param cb
* @return
*/
public Disposable startCountDown(final int allSecTimes, final RX2CountDownTimerCallback cb) {
//倒计时为200妙,
disposable = Flowable.intervalRange(0, allSecTimes, 0, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
if (null == cb) {
return;
}
cb.onNext(false, allSecTimes - (aLong + 1));
}
})
.doOnComplete(new Action() {
@Override
public void run() throws Exception {
if (null == cb) {
return;
}
cb.onNext(true, 0);
}
})
.subscribe();
return disposable;
}
/**
* 停止倒计时
*/
public void stopCountDown() {
if (null == disposable) {
return;
}
if (disposable.isDisposed()) {
return;
}
disposable.dispose();
}
}
附加:使用系统自带的CountDownTimer实现倒计时
private CountDownTimer cdTimer;
private void startCountDown() {
cdTimer = new CountDownTimer(3000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
gotoMain();
}
};
cdTimer.start();
}
private void stopCountDown() {
if (null == cdTimer) {
return;
}
cdTimer.cancel();
}