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

Take your career further with a raywenderlich.com 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.

Contributors

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 raywenderlich.com 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)
    creatureLiveData.postValue(creature)
  }
  fun attributeSelected(attributeType: AttributeType, position: Int) {
    when (attributeType) {
      AttributeType.INTELLIGENCE ->
      AttributeType.STRENGTH ->
      AttributeType.ENDURANCE ->
    }
    updateCreature()
  }
  fun drawableSelected(drawable: Int) {
    this.drawable = drawable
    updateCreature()
  }
private lateinit var viewModel: CreatureViewModel
viewModel = ViewModelProviders.of(this).get(CreatureViewModel::class.java)
viewModel.attributeSelected(AttributeType.INTELLIGENCE, position)
...
viewModel.attributeSelected(AttributeType.STRENGTH, position)
...
viewModel.attributeSelected(AttributeType.ENDURANCE, position)
viewModel.name = s.toString()
viewModel.drawableSelected(avatar.drawable)
if (viewModel.drawable != 0) hideTapLabel()
  private fun configureLiveDataObservers() {
    viewModel.getCreatureLiveData().observe(this, Observer { creature ->

    })
  }
    
      hitPoints.text = creature.hitPoints.toString()
        avatarImageView.setImageResource(creature.drawable)
        nameEditText.setText(creature.name)
     
creature?.let {
    ...
}
configureLiveDataObservers()

Reviews

Comments