Day64 of #100DaysOfCode

#CodeTogether Day 64/100

Hii folks 🙌

Today I will be continuing the same pathway in which we’ll learn to move data in ViewModel and populate it.

Unit 3: Navigation

Pathway 2: Architecture componentsSource

https://developer.android.com/courses/android-basics-kotlin/course

We will move forward in this pathway and will work on moving the data to the ViewModel.

  • We will move the data variables score, currentWordCount, currentScrambledWord to GameViewModel class.
class GameViewModel : ViewModel() {    private var score = 0
private var currentWordCount = 0
private var currentScrambledWord = "test"
...

Inside the ViewModel, the data should be editable, so they should be private and var. From outside the ViewModel, data should be readable, but not editable, so the data should be exposed as public and val. To achieve this behavior, Kotlin has a feature called a backing property.

A backing property allows you to return something from a getter other than the exact object.

// Declare private mutable variable that can only be modified
// within the class it is declared.

private var _count = 0

// Declare another public immutable field and override its getter method.
// Return the private property's value in the getter method.
// When count is accessed, the get() function is called and
// the value of _count is returned.

val count: Int
get() = _count
  • Now we will add the backing property to currentScrambledWord.
private var _currentScrambledWord = "test"
val currentScrambledWord: String
get() = _currentScrambledWord
  • In GameFragment, we will update the method updateNextWordOnScreen() to use the read-only viewModel property, currentScrambledWord.
private fun updateNextWordOnScreen() {
binding.textViewUnscrambledWord.text = viewModel.currentScrambledWord
}

That is all for Day64 ✅

Thanks for reading, See you tomorrow!

If you are reading my #100Days Journey, feel free to drop by ;)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store