package com.gingersoft.gsa.delivery_pick_mode.util

import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class RxTimerUtil {
    companion object {
        var mIntervalDisposable: Disposable? = null
        var timerDisposable: Disposable? = null
        /**
         * 执行定时任务
         */
        fun interval(block: () -> Unit, milliseconds: Long) {
            Observable.interval(0, milliseconds, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(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) {
                            mIntervalDisposable = d
                        }
                    })
        }

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

        fun cancelTimerDisposable() {
            if (timerDisposable != null && !timerDisposable!!.isDisposed) {
                timerDisposable!!.dispose()
            }
        }

        fun delayFun(block: () -> Unit, milliseconds: Long) {
            Observable.timer(milliseconds, TimeUnit.SECONDS)
                    .subscribe(object : Observer<Long> {
                        override fun onSubscribe(d: Disposable) {
                            timerDisposable = d
                        }

                        override fun onNext(t: Long) {
                            block()
                        }

                        override fun onError(e: Throwable) {
                        }

                        override fun onComplete() {

                        }
                    })
        }

    }
}