I have been trying to create an Object of ViewModel in an Activity but ViewModelProviders is deprecated So what\'s the alternative to create the ViewModel\'s object.
ViewModelProviders.of() has been deprecated.
Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.
Java
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
Kotlin
mainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
The simple option for the next several months is to stick with stable or beta versions. ViewModelProviders
is only deprecated starting with 2.2.0
, presently in an alpha03
release.
For when you do move to 2.2.0
or higher of the lifecycle dependencies, your options depend on your language:
If you are using Java, use the ViewModelProvider()
constructor, passing in your activity or fragment
If you are using Kotlin, there is supposed to be a by viewModels()
property delegate, though I am not finding it in the source code...
This code works for me
private lateinit var viewModel: MainViewModel
viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(MainViewModel::class.java)
Simply replace:
This:
boardViewModel = ViewModelProviders.of(this).get(BoardViewModel::class.java)
With this:
boardViewModel = ViewModelProvider(this).get(BoardViewModel::class.java)