Android 使用 Kotlin 和 RxJava 2.× 實現(xiàn)短信驗證碼倒計時效果

偷懶寫作,只貼代碼!

val timer:TextView = findViewById(R.id.textView) //這里的 timer 就是你要控制顯示倒計時效果的 TextView 
val mSubscription: Subscription? = null // Subscription 對象,用于取消訂閱關(guān)系,防止內(nèi)存泄露
//開始倒計時,用 RxJava2 實現(xiàn)
    private fun timer() {
        val count = 59L
        Flowable.interval(0, 1, TimeUnit.SECONDS)//設(shè)置0延遲,每隔一秒發(fā)送一條數(shù)據(jù)
                .onBackpressureBuffer()//加上背壓策略
                .take(count) //設(shè)置循環(huán)次數(shù)
                .map{ aLong ->
                    count - aLong //
                }
                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI線程
                .subscribe(object : Subscriber<Long> {
                    override fun onSubscribe(s: Subscription?) {
                        timer.isEnabled = false//在發(fā)送數(shù)據(jù)的時候設(shè)置為不能點擊
                        timer.textColor = resources.getColor(Color.GRAY)//背景色設(shè)為灰色
                        mSubscription = s
                        s?.request(Long.MAX_VALUE)//設(shè)置請求事件的數(shù)量,重要,必須調(diào)用
                    }

                    override fun onNext(aLong: Long?) {
                        timer.text = "${aLong}s后重發(fā)" //接受到一條就是會操作一次UI
                    }

                    override fun onComplete() {
                        timer.text = "點擊重發(fā)"
                        timer.isEnabled = true
                        timer.textColor = Color.WHITE
                        mSubscription?.cancel()//取消訂閱,防止內(nèi)存泄漏
                    }

                    override fun onError(t: Throwable?) {
                        t?.printStackTrace()
                    }
                })
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容