architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

About the livedata

Open yangwuan55 opened this issue 6 years ago • 1 comments

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.

private void subscribeToModel(final ProductViewModel model) {

        // Observe product data
        model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
            @Override
            public void onChanged(@Nullable ProductEntity productEntity) {
                model.setProduct(productEntity);
            }
        });

        // Observe comments
        model.getComments().observe(this, new Observer<List<CommentEntity>>() {
            @Override
            public void onChanged(@Nullable List<CommentEntity> commentEntities) {
                if (commentEntities != null) {
                    mBinding.setIsLoading(false);
                    mCommentAdapter.setCommentList(commentEntities);
                } else {
                    mBinding.setIsLoading(true);
                }
            }
        });
 }


yangwuan55 avatar Apr 18 '19 08:04 yangwuan55

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

yangwuan55 avatar Apr 18 '19 08:04 yangwuan55