Solution to Deprecated method ViewModelProviders#of

The easy solution for this app is to change remove the ViewModelProviders usage. The ViewModel can be created using the default factory directly via the ViewModelProvider.

private val quizViewModel: QuizViewModel by lazy {
  ViewModelProvider(this@QuizActivity).get(QuizViewModel::class.java)
}

However, this will not suffice for more complex ViewModels that depend upon other resources. For these situations, we will need to create our own Factory class. For this example, the factory would like follows.

// QuizViewModelFactory.kt
class QuizViewModelFactory : ViewModelProvider.Factory {
  override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    return modelClass.getConstructor().newInstance()
  }
}

Now inside of QuizActivity, we get an instance of QuizViewModel by first creating the factory.

// QuizActivity.kt
private val quizViewModel: QuizViewModel by lazy {
  val factory = QuizViewModelFactory()
  ViewModelProvider(this@QuizActivity, factory).get(QuizViewModel::class.java)
}
4 Likes