LiveData学习
ViewModel中持有一個數據對象
//將“秒鐘”這個字段用MutableLiveData包裝起來
private var currentSecond: MutableLiveData<Int>? = null
fun getCurrentSecond(): LiveData<Int>? {
? ? if (currentSecond == null) {
? ? ? ? currentSecond = MutableLiveData(0)
? ? }
? ? return currentSecond
}
? ??
? ??
// 通過LiveData.observe()實現對ViewModel中數據變化的觀察
liveData.observe(this, object : Observer<Int> {
? ? override fun onChanged(@Nullable second: Int) {
? ? ? ? //收到回調后更新UI界面
? ? ? ? (findViewById(R.id.tv_timer) as TextView).text = "TIME:$second"
? ? }
})
當數據變更時會自動通知監聽者
fun startTiming() {
? ? viewModelScope.launch {
? ? ? ? repeat(100){
? ? ? ? ? ? delay(1000)
? ? ? ? ? ? val data: MutableLiveData<Int> = getCurrentSecond() as MutableLiveData<Int>
? ? ? ? ? ? data.value = data.value!! + 1
? ? ? ? ? ? println("Current value is ${data.value}")
? ? ? ? }
? ? }
}
總結
以上是生活随笔為你收集整理的LiveData学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Databinding学
- 下一篇: 每日一道算法题-寻找丑数