Android rxjava 定时器

xiaoxiao2021-02-28  12

package com.hadex.xq.utils import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableObserver import net.funbling.com.baselibrary.utils.sys.LogUtils import java.util.concurrent.TimeUnit /** * 倒计时工具 */ class TimeMeterUtils private constructor() { //默认10S private var time: Long = 10L private var observable: Observable<Long>? = null private var mCompositeDisposable = CompositeDisposable() companion object { fun getInstance() = Holder.INSTANCE } private object Holder { val INSTANCE = TimeMeterUtils() } /** * interval设置0延迟,每隔一秒发送一条数据 * take 设置循环time */ private fun getTimeMeter(): Observable<Long> { return Observable.interval(0, 1, TimeUnit.SECONDS).take(time).map { t -> time - t }.observeOn(AndroidSchedulers.mainThread()) } private fun getDisposable(): DisposableObserver<Long> { return object : DisposableObserver<Long>() { override fun onComplete() { LogUtils.i("TimeMeterUtils.onComplete()") } override fun onNext(t: Long) { LogUtils.i("TimeMeterUtils.onNext(t: $t)") } override fun onError(e: Throwable) { LogUtils.i("TimeMeterUtils.onError(${e.message})") } } } fun start(time: Long, disposable: DisposableObserver<Long>) { this.time = time if (observable == null) { getNewObervable(disposable) } else { mCompositeDisposable.clear() getNewObervable(disposable) } } private fun getNewObervable(disposable: DisposableObserver<Long>) { observable = getTimeMeter() var observer = disposable observable!!.subscribe(observer) mCompositeDisposable.add(observer) } fun stop() { observable?.let { mCompositeDisposable.clear() } } }
转载请注明原文地址: https://www.6miu.com/read-2250189.html

最新回复(0)