偷懶寫作,只貼代碼!
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()
}
})
}