Viewmodel

To use viewmodel first need to add gradle dependency

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0' 

make new kotlin file with appropriate viewmodel name

class SampleViewModel : ViewModel()

Add init block and override onCleared. Add log statements to both

Create a field for the viewmodel class we created in the recquired activity

private lateinit var sampleviewmodel: SampleViewModel

Inside oncreate of class or fragment initialize viewmodel

viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)

now place the logic codes in the viewmodel class

view model should never hold references to activities or fragments.

UI controller(activity) should be as simple as possible

Last updated

Was this helpful?