小言_互联网的博客

ViewModel LiveData 使用初体验

306人阅读  评论(0)

背景 Fragment 希望不用那么多代码在Fragment中。所以推出了ViewModel加载数据的方式。更加高度的解耦

生命周期

使用


  
  1. package com.anguomob.love.activity.ui.my
  2. import androidx.lifecycle.LiveData
  3. import androidx.lifecycle.MutableLiveData
  4. import androidx.lifecycle.ViewModel
  5. import com.anguomob.love.bean.UserInfo
  6. import com.anguomob.love.common.PassportManager
  7. import com.anguomob.love.net.usecase.PassportUseCase
  8. import io.reactivex.disposables.CompositeDisposable
  9. class MyViewModel : ViewModel() {
  10. override fun onCleared() {
  11. super.onCleared()
  12. }
  13. private val _text = MutableLiveData<UserInfo>()
  14. private val _error = MutableLiveData<Throwable>()
  15. var dataList: LiveData<UserInfo> = _text
  16. var error: LiveData<Throwable> = _error
  17. val mDisposable: CompositeDisposable = CompositeDisposable()
  18. init {
  19. val subscribe =
  20. PassportUseCase().refreshUserInfo(PassportManager.getInstance().getUid()).subscribe({
  21. it?.let {
  22. _text.value=it;
  23. }
  24. }, {
  25. _error.value=it
  26. })
  27. mDisposable.add(subscribe)
  28. }
  29. }

创建 ViewModel 类 并直接加载数据

在Fragment中需要的地方

 

initData里面把代码用上

    private lateinit var dashboardViewModel: MyViewModel

  
  1. dashboardViewModel =
  2. ViewModelProvider(this). get(MyViewModel:: class.java)
  3. dashboardViewModel.dataList.observe(viewLifecycleOwner, Observer {
  4. it?. let {
  5. PassportManager.getInstance().saveUserInfo(it)
  6. Glide. with(this)
  7. .load(it.avatar)
  8. .placeholder(getDefaultPlace(it.sex))
  9. .transition(DrawableTransitionOptions.withCrossFade())
  10. .into(mIvFDUpload)
  11. mTvFdNickName.text = it.nick_name;
  12. }
  13. })
  14. dashboardViewModel. error.observe(viewLifecycleOwner, Observer {
  15. it?. let {
  16. TipsToast.showTips(activity, ApiErrorCodeDesc.getErrorMsg(it))
  17. }
  18. })

 


转载:https://blog.csdn.net/mp624183768/article/details/112602627
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场