Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

android - ViewModelProviders is deprecated in 1.1.0

Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

val model = ViewModelProviders.of(this).get(MyViewModel::class.java)

When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Going to the documentation for ViewModelProviders, I saw a comment saying:

This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

The problem is, when trying to use ViewModelProvider.AndroidViewModelFactory, cannot find an equivalent of method to get the instance of the ViewModel.

What i tried doing:

ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)

Hence the name of the method create, I get a new instance of the ViewModel every-time I call it, which is not what I am after.

Any ideas what is the replacement of deprecated code above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I use lifecycle-extensions 2.2.0 version:

implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" 

It should be work, using ViewModelProvider constructor.

// With ViewModelFactory   
val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java)


//Without ViewModelFactory
val viewModel = ViewModelProvider(this).get(YourViewModel::class.java)

2020/5/15 Update

I find another elegant way to achieve, Android KTX can help

implementation "androidx.fragment:fragment-ktx:1.2.4"
val viewmodel: MYViewModel by viewModels()
val viewmodel: MYViewModel by viewModels { myFactory } //With factory

Ref: https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels

2020/06/25: corrected the case of the delegate


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...