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}")
}
}
}