问题
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.
回答1:
Simply replace:
This:
boardViewModel = ViewModelProviders.of(this).get(BoardViewModel::class.java)
With this:
boardViewModel = ViewModelProvider(this).get(BoardViewModel::class.java)
回答2:
ViewModelProviders.of() has been deprecated. You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality. (aosp/1009889)
Please click here to see the solution
回答3:
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 fragmentIf you are using Kotlin, there is supposed to be a
by viewModels()
property delegate, though I am not finding it in the source code...
回答4:
If you're using Kotlin, instead of:
private lateinit var viewModel: EntityGridViewModel
[...]
// Deprecated
viewModel = ViewModelProviders.of(this).get(EntityGridViewModel::class.java)
You can use the nicer:
private val viewModel: EntityGridViewModel by viewModels()
回答5:
ViewModelProviders.of() has been deprecated.
Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
回答6:
Declare your viewmodel :
private lateinit var mYourViewModel: YourViewModel
Intialize you viewmodel : (If in activity then pass this)
mYourViewModel= YourViewModel(this).get(YourViewModel::class.java)
Observer viewModel : (If in activity pass "this")
mYourViewModel.yourMethodInViewModel().observe(this,
Observer<Boolean> { isExhausted ->
}
})
Observer viewModel : (If in fragment pass "viewLifecycleOwner")
mYourViewModel.yourMethodInViewModel().observe(viewLifecycleOwner,
Observer<Boolean> { isExhausted ->
// do stuff with this
}
})
Hope this will help.
来源:https://stackoverflow.com/questions/57534730/as-viewmodelproviders-of-is-deprecated-how-should-i-create-object-of-viewmode