xinyang123123/AndroidDemo

使用rxjava计时

Opened this issue · 1 comments

#谢谢作者的代码
添加rxjava2做计时,添加停止接口

compile "io.reactivex.rxjava2:rxjava:2.1.7"
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'


private Flowable<Long> mFlowable; //创建一个上游 Observable:
private Disposable mDisposable;

/**停止计时**/
public void  stopDownTime(){
    if (mDisposable !=null){
        mDisposable.dispose();
    }
}
/**
 * 设置到最大进度的时间
 *
 * @param time 倒计时时间 毫秒值
 */
public void startDownTime(final long time, final OnFinishListener listener) {
    mMaxProgress = 100;
    mFlowable = Flowable.interval((int) (time / mMaxProgress), TimeUnit.MILLISECONDS)
            .map(new Function<Long, Long>() {
                @Override
                public Long apply(@NonNull Long aLong) throws Exception {
                   mProgress = (100- aLong);//顺时针
                    //  mProgress = aLong;//逆时针
                    ProgressView.this.postInvalidate();
                    return (int)mMaxProgress - aLong;
                }
            }).take( (int)mMaxProgress + 1 )
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread());

    mDisposable = mFlowable.subscribe(new Consumer<Long>() {
        @Override
        public void accept(Long aLong) throws Exception {
            if (aLong ==0){
                listener.onFinish();
            }
        }
    });

}

谢谢建议,还没具体了解过RxJava。这两天有空看下~