Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModelProviders is deprecated in 2.2.0

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

like image 921
Sudip Sadhukhan Avatar asked Feb 21 '20 05:02

Sudip Sadhukhan


People also ask

Is Viewmodelproviders deprecated?

This class is deprecated.

What can I use instead of Viewmodelproviders?

The android. arch Architecture Components packages are no longer maintained. They have been superseded by the corresponding androidx.

How do you use ViewModelProvider in Kotlin?

Use the 'by viewModels()' Kotlin property delegate or ViewModelProvider , passing in the fragment. This function is deprecated. Use the 'by viewModels()' Kotlin property delegate or ViewModelProvider , passing in the activity. of (fragment: Fragment, factory: ViewModelProvider.

What is the use of ViewModelFactory?

ViewModelFactory uses factory to create objects while Factory method is a method that return the copy of the same class.


Video Answer


3 Answers

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

like image 89
aksBD Avatar answered Oct 28 '22 08:10

aksBD


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);
like image 41
Chirag Bhuva Avatar answered Oct 28 '22 08:10

Chirag Bhuva


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 ViewModels. For example:

val model: MyViewModel by viewModels()
like image 24
Ryan M Avatar answered Oct 28 '22 06:10

Ryan M