— Android, Mobile — 1 min read
Bind observable variables and action by View Model. The relationship between View Model and View is 1-many which means that many Views can be associated with 1 View Model.
In View layer, We handle 3 steps:
1// Initialize ViewModel without factory2 final ProductListViewModel viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);3 // Initialize ViewModel with factory4 final ProductViewModel model = new ViewModelProvider(this, factory).get(ProductViewModel.class);
1mBinding.productsSearchBtn.setOnClickListener(v -> {2 Editable query = mBinding.productsSearchBox.getText();3 viewModel.setQuery(query);4 });
1// Update the list of products when the underlying data changes.2 viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {3 @Override4 public void onChanged(@Nullable List<ProductEntity> myProducts) {5 if (myProducts != null) {6 mBinding.setIsLoading(false);7 mProductAdapter.setProductList(myProducts);8 } else {9 mBinding.setIsLoading(true);10 }11 }12 });
ViewModel contains Models and prepare the observable data for the View. It's middle man to interact between View and Model. One thing to keep in mind is that ViewModel will not bind to the View
DataRepository
from Dependencies Injection (DI) or from Application classLiveData
to View Layer1// By this way, we can pass product ID into ViewModel2 public static class Factory extends ViewModelProvider.NewInstanceFactory {3
4 @NonNull5 private final Application mApplication;6
7 private final int mProductId;8
9 private final DataRepository mRepository;10
11 public Factory(@NonNull Application application, int productId) {12 mApplication = application;13 mProductId = productId;14 mRepository = ((BasicApp) application).getRepository();15 }16
17 @SuppressWarnings("unchecked")18 @Override19 @NonNull20 public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {21 return (T) new ProductViewModel(mApplication, mRepository, mProductId);22 }23 }
LiveData
instead of raw Object.