1. Make internal and external versions of word
and score
:
Open up GameViewModel. The internal version should be a MutableLiveData, have an underscore in front of its name, and be private. The underscore is our convention for marking the variable as the internal version of a variable.
The external version should be a LiveData and not have an underscore in front of its name.
For example, here’s the internal and external version of score
:
// internal
private val _score = MutableLiveData<Int>()
//external
val score: LiveData<Int>
2. Make a backing property for the external version that returns the internal MutableLiveData as a LiveData:
Kotlin automatically makes getters and setters for your fields. If you want to override the getter for score
, you can do so using a backing property. You've actually already defined your backing properties (_score
and _word
). Now you can take your public versions of the variables (score
and word
) and override get
to return the backing properties.
For example, here’s the full encapsulated score
:
private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
get() = _score
By making the return type LiveData rather than MutableLiveData, you've exposed only score
and word
as LiveData.
3. In the view model, use the internal, mutable versions of score
and word
:
In GameViewModel, update the code so that you use the mutable versions, _score
and _word
, throughout the view model. When you’re finished, make sure to run your code!
Comments
Post a Comment