Android中LiveData组件在ViewModel组件中的使用

14 篇文章 0 订阅
9 篇文章 1 订阅

LiveData的优势

  • 确保界面符合数据状态
  • 不会发生内存泄漏
  • 不会因Activity停止而导致崩溃
  • 不用手动处理生命周期
  • 数据始终保持最新状态
  • 适当的配置修改
  • 共享资源
    //版本号根据实际情况添加
	implementation "androidx.fragment:fragment-ktx:1.3.2"
    implementation 'androidx.activity:activity-ktx:1.3.0-alpha05'

版本号参考:

Activity版本

Fragment版本

1.ViewModel类中LiveData创建

  • 不需要使用context时,则继承ViewModel类就可以

    class MainViewModel: ViewModel(){
    	var userName: MutableLiveData<Int> = MutableLiveData()
        val currentName: MutableLiveData<String> by lazy {
            MutableLiveData<String>()
        }
    }
    
  • ViewModel中如果需要使用context,则继承AndroidViewModel

    class MainViewModel(application: Application):AndroidViewModel(application){
    }
    

**2.Activity中通过ViewModel**的使用LiveData

Kotlin中获取实例化ViewModel对象的两种方式
  • 第一种:通过ViewModelProvider方式获取

    //不需要context
    viewModel = ViewModelProvider(this).get(CharactersViewModel::class.java)
    //需要传入context
    val viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(MainViewModel::class.java)
    
  • 第二种:通过by viewModels()方式获取

    Activity中获取

    val model: MyViewModel by viewModels()
    

    Fragment中获取方式

    //获取当前fragment依赖的Activity的ViewModel,与activity的数据是共享的
    val viewModel: MainViewModel by activityViewModels()
    //获取自己当前fragment使用的ViewModel,与activity中的ViewModel数据无关
    val viewModel: MainViewModel by viewModels()
    //针对viewModel中的对象进行监听
    viewModel.currentName.observe(viewLifecycleOwner, {
    	// update UI
    })
    
ViewModelLiveData的更新
//UI线程中更新内容
viewModel.currentName.value = "UI线程LiveData更新内容"
//异步方式更新内容
viewModel.currentName.postValue("子线程中LiveData更新内容")
监听LiveData的方式

Activityfragmentlamda表达式监听

viewModel.userName.observe(this, {
	Log.i("tag", it)
})

带入参数方式监听

val nameObserver = Observer<String> { newName ->
	Log.i("tag", newName)
}
viewModel.currentName.observe(this, nameObserver)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值