Simple ViewModel

--

Photo by Félix Lam on Unsplash

0. Add dependency:

  1. Create MainViewModel.class:

2. Modify MainActivity.class:

3. activity_main.xml:

4. Gif: TextView data is being saved after configuration change e.g. screen rotation:

Passing objects to viewModel using Factory.

  1. Change viewModel with the parameterised constructor:

2. Create factory class where we can create viewModel as we like:

3. Change MainActivity class by adding MainViewModelFactory object, initialise it and set to ViewModelProvider as a second parameter:

4. Gif:

First we change configuration with the default text which was passed to viewModel during creation.

Then change configuration with the newly set text.

--

--