如何在CountdownTimer完成时通知Observable

时间:2017-07-30 20:53:25

标签: android kotlin rx-java rx-kotlin

我有一个自定义的Android TextView,通过CountDownTimer显示游戏中剩余的时间

class CountdownTextView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {

    private lateinit var countDownTimer: CountDownTimer
    private lateinit var onFinishObservable: Observable<Unit>

    fun setTime(initTime: Int) {
        this.text = "$initTime:00"
        countDownTimer = object : CountDownTimer((initTime *1000).toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
            val minutes = millisUntilFinished / 60000
            val seconds = (millisUntilFinished % 60000) / 1000
            if (seconds / 10 > 0) {
                text = "$minutes:${(millisUntilFinished % 60000) / 1000}"
            } else {
                text = "$minutes:0${(millisUntilFinished % 60000) / 1000}"
            }
        }

        override fun onFinish() {

        }
    }


    fun startCountdown() {
        countDownTimer.start()
    }
}

当调用countDownTimer的onFinish()方法时,如何设置一个发出值的observable?我需要这个,以便在主活动上,我可以订阅该observable并在countdowntimer到期时执行必要的操作。

1 个答案:

答案 0 :(得分:0)

您可以提供Subject

val onFinishObservable = CompletableSubject.create()

override fun onFinish() {
    onFinishObservable.onComplete()
}

或者您可以将Rx用作计时器而不是CountDownTimer

fun countDownTimer(
        time: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS,
        tick: Long = 1, tickUnit: TimeUnit = TimeUnit.MILLISECONDS
): Observable<Long> {
    val timeNanos = timeUnit.toNanos(time).also { require(it >= 0) }
    val tickNanos = tickUnit.toNanos(tick).also { require(it > 0) }
    val ticks = timeNanos / tickNanos
    return Observable
        .intervalRange(
            1L, ticks, timeNanos % tickNanos, tickNanos, TimeUnit.NANOSECONDS)
        .map { ticks - it }
        .startWith(ticks)
}

fun start(time: Long, timeUnit: TimeUnit = TimeUnit.SECONDS): Completable {
    timerSubscription?.dispose()
    val timer = countDownTimer(time, timeUnit, tickUnit = TimeUnit.SECONDS)
    timerSubscription = timer.subscribe {
        text = String.format("%d:%02d", it / 60, it % 60)
    }
    return timer.ignoreElements()
}

无论哪种方式,调用者都可以订阅Completable