Currently I update androidx.lifecycle:lifecycle-extensions
version from 2.2.0-alpha01
to 2.2.0
and it shows that ViewModelProviders is depricated. So what is the alternative way to use ViewModelProviders in kotlin?
Asked
Active
Viewed 7,409 times
7

Sudip Sadhukhan
- 1,784
- 12
- 21
-
1`ViewModelProvider(this).get(ChatViewModel::class.java)` – Kapta Feb 21 '20 at 09:35
3 Answers
12
older version
var viewModel = ViewModelProviders.of(this).get(BaseViewModel::class.java)
Now alternative
In java
viewModel = ViewModelProvider(this).get(BaseViewModel.class);
In kotlin
var viewModel = ViewModelProvider(this).get(BaseViewModel::class.java)
Refs - https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders

aksBD
- 189
- 1
- 6
-
2in Java "viewModel = new ViewModelProvider(this).get(BaseViewModel.class);" – Max Gabderakhmanov Aug 10 '20 at 20:59
8
For example, if you are using an older version.
MyViewModel myViewModel = new ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "Your string parameter")).get(MyViewModel.class);
For Example, for the latest version
MyViewModel myViewModel = new ViewModelProvider(this, viewModelFactory).get(MyViewModel.class);
OR, Use ViewModelStore link
MyViewModel myViewModel = new ViewModelProvider(getViewModelStore(), viewModelFactory).get(MyViewModel.class);

Chirag Bhuva
- 851
- 7
- 14
5
As it says in the documentation, you can now simply use the ViewModelProvider
constructors directly. It should be mostly a matter of changing ViewModelProviders.of(
to ViewModelProvider(
, but you can see the complete listing of exactly which new methods correspond to which old ones in the documentation as well.
In Kotlin, you can also use the by viewModels()
property delegate within your Activity
/Fragment
to get individual ViewModel
s. For example:
val model: MyViewModel by viewModels()

Ryan M
- 18,333
- 31
- 67
- 74