【问题标题】:How to notify Observable when CountdownTimer is finishedCountdownTimer 结束时如何通知 Observable
【发布时间】:2017-07-30 20:53:25
【问题描述】:

我有一个自定义的 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 并在倒数计时器到期时执行必要的操作。

【问题讨论】:

    标签: android kotlin rx-java rx-kotlin


    【解决方案1】:

    您可以提供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

    【讨论】:

    • 我使用了可完成的主题,并且效果很好。关于响应式扩展,有很多东西要学! 1. 倒数计时器使用RX理论上会提高性能吗? 2. 我很难理解 RxTimer 是如何完成的。
    • 哦 nvm " val timeNanos = timeUnit.toNanos(time).also { require(it >= 0) }" " " val tickNanos = tickUnit.toNanos(tick).also { require(it > 0 ) } " 一定是在耍花招
    • @ArsalaBangash 在这种情况下,使用基于 Rx 的计时器并没有直接的好处,但它更灵活,如果您将它连接到其他东西可能会很有用。
    猜你喜欢
    • 2020-04-25
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2020-07-08
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多