发布于 5年前

Android RxKotlin 执行定时任务

 class RxTimerUtil {
    companion object {
        var mDisposable: Disposable? = null

        /**
         * 执行定时任务
         */
        fun timer(block: () -> Unit, milliseconds: Long) {
            Observable.timer(milliseconds, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<Long> {
                        override fun onError(e: Throwable) {}
                        override fun onComplete() {}
                        override fun onNext(t: Long) {
                            block()
                        }

                        override fun onSubscribe(d: Disposable) {
                            mDisposable = d
                        }
                    })
        }

        /**
         * 取消定时器
         */
        fun cancel() {
            if (mDisposable != null && !mDisposable!!.isDisposed) {
                mDisposable!!.dispose()
            }
        }

    }
}
©2020 edoou.com   京ICP备16001874号-3