LiveData学习

这篇博客介绍了如何在Android中利用ViewModel和LiveData进行数据绑定。通过创建一个MutableLiveData对象来存储秒数,并在ViewModel中更新这个值。每当数据变化时,LiveData会自动通知观察者,从而更新UI界面。在startTiming函数中,展示了如何每秒增加秒数并打印当前值。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值