Day71 of #100DaysOfCode
Hii folks 🙌
Today I will be continuing the same pathway in which we’ll attach the LiveData to score and wordCount.
Unit 3: Navigation
Pathway 2: Architecture componentsSource
https://developer.android.com/courses/android-basics-kotlin/course
Use LiveData with ViewModel
We will learn how to wrap any data with LiveData
, by converting the current word in the GameViewModel
to LiveData
. Later we will add an observer to these LiveData
objects.
MutableLiveData
is the mutable version of the LiveData
, that is, the value of the data stored within it can be changed.
- In
GameViewModel
, we will change the type of the variable_currentScrambledWord
toMutableLiveData<String>
.LiveData
andMutableLiveData
are generic classes, so we need to specify the type of data that they hold. - Now we will change the variable type of
_currentScrambledWord
toval
because the value of theLiveData
/MutableLiveData
object will remain the same, and only the data stored within the object will change.
private val _currentScrambledWord = MutableLiveData<String>()
- Now we will change the backing field,
currentScrambledWord
type toLiveData<String>
, because it is immutable.
val currentScrambledWord: LiveData<String>
get() = _currentScrambledWord
- To access the data within a
LiveData
object, we use thevalue
property. InGameViewModel
inside thegetNextWord()
method, within theelse
block, change the reference of_currentScrambledWord
to_currentScrambledWord.value
.
private fun getNextWord() {
...
} else {
_currentScrambledWord.value = String(tempWord)
...
}
}
Now we will attach the observer to the LiveData
object
private fun onSubmitWord() {
val playerWord = binding.textInputEditText.text.toString()
if (viewModel.isUserWordCorrect(playerWord)) {
setErrorTextField(false)
if (!viewModel.nextWord()) {
showFinalScoreDialog()
}
} else {
setErrorTextField(true)
}
}
- And, we will attach an observer for
currentScrambledWord
LiveData
. InGameFragment
at the end of the callbackonViewCreated()
, call theobserve()
method oncurrentScrambledWord
.
// Observe the currentScrambledWord LiveData.
viewModel.currentScrambledWord.observe()
- Now we will add a lambda as a second parameter with
newWord
as a function parameter. ThenewWord
will contain the new scrambled word value.
// Observe the scrambledCharArray LiveData, passing in the LifecycleOwner and the observer.
viewModel.currentScrambledWord.observe(viewLifecycleOwner,
{ newWord ->
})
- In the function body of the lambda expression, we will assign newWord to the scrambled word text view.
// Observe the scrambledCharArray LiveData, passing in the LifecycleOwner and the observer.
viewModel.currentScrambledWord.observe(viewLifecycleOwner,
{ newWord ->
binding.textViewUnscrambledWord.text = newWord
})
That is all for Day71 ✅
Thanks for reading, See you tomorrow!
If you are reading my #100Days Journey, feel free to drop by ;)