Skip to content
KYND Dev

Notes on Android MVVM

Android, Mobile1 min read

View Layer

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 with or without factory
1// Initialize ViewModel without factory
2 final ProductListViewModel viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);
3 // Initialize ViewModel with factory
4 final ProductViewModel model = new ViewModelProvider(this, factory).get(ProductViewModel.class);
  1. Call ViewMode directly from View to send user Event if user input:
1mBinding.productsSearchBtn.setOnClickListener(v -> {
2 Editable query = mBinding.productsSearchBox.getText();
3 viewModel.setQuery(query);
4 });
  1. Subscribe UI, we can observe the Model by:
1// Update the list of products when the underlying data changes.
2 viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {
3 @Override
4 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 Layer

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

  • ViewModel object extend AndroidViewModel object.
  • Get DataRepository from Dependencies Injection (DI) or from Application class
  • Expose data using LiveData to View Layer

We can inject dependencies into ViewModels from View by using Factory

1// By this way, we can pass product ID into ViewModel
2 public static class Factory extends ViewModelProvider.NewInstanceFactory {
3
4 @NonNull
5 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 @Override
19 @NonNull
20 public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
21 return (T) new ProductViewModel(mApplication, mRepository, mProductId);
22 }
23 }

Model & Repository

  • Act the same with MVP except they can return LiveData instead of raw Object.

Reference:

Android Architecture Components Basic