> For the complete documentation index, see [llms.txt](https://jobinjj.gitbook.io/tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jobinjj.gitbook.io/tutorials/android-jetpack/viewmodel.md).

# 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()
```

&#x20;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.&#x20;

UI controller(activity) should be as simple as possible
