Open yangwuan55 opened 5 years ago
The ViewModel is a role who handle the relationship between UI and Model,so the viewmodel should prepare the data for UI and Model,like the Presenter of MVP or Controller of MVC.
For example viewmodel receive a data from server,it contains name and photo(url).
If we don't use databinding,we should write these code in fragment or activity.
fun initViews() {
viewmodel.getName().obsever(this) {
name->
tvName.setText(name)
}
//Attention viewmodel give a bitmap to the view,viewmodel should download the image use the image url.
viewmodel.getPhoto().observer(this) {
bitmap->
ivPhoto.setImageBitmap(bitmap)
}
}
If we use databinding,we should wirte these code in viewmodel.
val MutableLiveData<String> name = new MutableLiveData<>();
val MutableLiveData<Bitmap> photo = new MutableLiveData<>();
fun initViewModel() {
getTheDataFromServer {
data->
name.postValue(data.name)
downloadImage(data.photo) {
bitmap->
photo.postValue(bitmap)
}
}
}
Why is this part of the code written in fragment?I think it could written in viewmodel. ViewModel should use the ObservableFiled or LiveData to update UI,and I think livedata is not a UI data sometimes,it should should be treated by viewmodel and set data to the view. Fragment or activity is a operating unit for system,they do something like the life cycle or registration system events. So,I think the samples is a wrong guidance for the mvvm.