背景 Fragment 希望不用那么多代码在Fragment中。所以推出了ViewModel加载数据的方式。更加高度的解耦
生命周期
使用
-
package com.anguomob.love.activity.ui.my
-
-
import androidx.lifecycle.LiveData
-
import androidx.lifecycle.MutableLiveData
-
import androidx.lifecycle.ViewModel
-
import com.anguomob.love.bean.UserInfo
-
import com.anguomob.love.common.PassportManager
-
import com.anguomob.love.net.usecase.PassportUseCase
-
import io.reactivex.disposables.CompositeDisposable
-
-
class MyViewModel : ViewModel() {
-
override
fun onCleared() {
-
super.onCleared()
-
}
-
private
val _text = MutableLiveData<UserInfo>()
-
private
val _error = MutableLiveData<Throwable>()
-
var dataList: LiveData<UserInfo> = _text
-
var error: LiveData<Throwable> = _error
-
val mDisposable: CompositeDisposable = CompositeDisposable()
-
init {
-
val subscribe =
-
PassportUseCase().refreshUserInfo(PassportManager.getInstance().getUid()).subscribe({
-
it?.let {
-
_text.value=it;
-
-
}
-
-
}, {
-
_error.value=it
-
-
})
-
mDisposable.add(subscribe)
-
}
-
-
-
}
创建 ViewModel 类 并直接加载数据
在Fragment中需要的地方
initData里面把代码用上
private lateinit var dashboardViewModel: MyViewModel
-
dashboardViewModel =
-
ViewModelProvider(this).
get(MyViewModel::
class.java)
-
dashboardViewModel.dataList.observe(viewLifecycleOwner, Observer {
-
it?.
let {
-
PassportManager.getInstance().saveUserInfo(it)
-
Glide.
with(this)
-
.load(it.avatar)
-
.placeholder(getDefaultPlace(it.sex))
-
.transition(DrawableTransitionOptions.withCrossFade())
-
.into(mIvFDUpload)
-
-
-
mTvFdNickName.text = it.nick_name;
-
-
}
-
})
-
-
dashboardViewModel.
error.observe(viewLifecycleOwner, Observer {
-
it?.
let {
-
TipsToast.showTips(activity, ApiErrorCodeDesc.getErrorMsg(it))
-
}
-
})
转载:https://blog.csdn.net/mp624183768/article/details/112602627
查看评论