1. Add lifecycle-extensions gradle dependency:
In the Module: app build.gradle file, add the lifecycle-extensions dependency. You can find the most current version of the dependency here.
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
Don't forget to sync!
2. Create the GameViewModel
class, extending ViewModel
: Create a new file called GameViewModel.kt
in the java/com.example.android.guesstheword/game
package. Then in this file, create a class GameViewModel that extends ViewModel:
class GameViewModel : ViewModel()
3. Add init block and override onCleared
. Add log statements to both:
Make an init block that prints out a log saying “GameViewModel created!”. Then override onCleared so you can track the lifetime of this ViewModel. You can use the keyboard shortcut Ctrl + O to do the override. Then add the log statement saying "GameViewModel destroyed!" to onCleared.
4.Create and initialize a GameViewModel
, using ViewModelProviders
. Add a log statement:
Back in GameFragment use lateinit
to create a field for GameViewModel called viewModel
. Then in onCreateView, request the current GameViewModel using the ViewModelProviders
class:
viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)
Add a log statement before calling viewModel, saying "Called ViewModelProviders.of"
Comments
Post a Comment