Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Pro subscription. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it’s simply the best investment you can make in your development career.

Build the ViewModel Pro

The student materials have been reviewed and are updated as of July 2022.

See how to use the Android Architecture Component ViewModel and LiveData classes to create a ViewModel layer for your app.


Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a Professional subscription.

With our Model and View in place, we’ll now turn to creating a ViewModel for the Add Creature screen named CreatureViewModel.

class CreatureViewModel : ViewModel() {

class CreatureViewModel(private val generator: CreatureGenerator = CreatureGenerator()) : ViewModel() {

  private val creatureLiveData = MutableLiveData<Creature>()
  fun getCreatureLiveData(): LiveData<Creature> = creatureLiveData
  var name = ""
  var intelligence = 0
  var strength = 0
  var endurance = 0
  var drawable = 0
lateinit var creature: Creature
  fun updateCreature() {
    val attributes = CreatureAttributes(intelligence, strength, endurance)
    creature = generator.generateCreature(attributes, name, drawable)
  fun attributeSelected(attributeType: AttributeType, position: Int) {
    when (attributeType) {
      AttributeType.INTELLIGENCE ->
      AttributeType.STRENGTH ->
      AttributeType.ENDURANCE ->
  fun drawableSelected(drawable: Int) {
    this.drawable = drawable
private lateinit var viewModel: CreatureViewModel
viewModel = ViewModelProviders.of(this).get(
viewModel.attributeSelected(AttributeType.INTELLIGENCE, position)
viewModel.attributeSelected(AttributeType.STRENGTH, position)
viewModel.attributeSelected(AttributeType.ENDURANCE, position) = s.toString()
if (viewModel.drawable != 0) hideTapLabel()
  private fun configureLiveDataObservers() {
    viewModel.getCreatureLiveData().observe(this, Observer { creature ->

      hitPoints.text = creature.hitPoints.toString()
creature?.let {