Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get ViewModel scoped to this Fragment (fragment-ktx)
//my sample
version_fragment = '1.2.0-alpha01'
implementation "androidx.fragment:fragment-ktx:${version_fragment}"
// Get a reference to the ViewModel scoped to this Fragment (fragment-ktx)
val viewModel by viewModels<DetailViewModel> {DetailViewModelFactory(marsProperty, application)}
//default provider (viewmodel without args)
val viewModel by viewModels<OverviewViewModel>()
class DetailViewModelFactory(
private val marsProperty: MarsProperty,
private val application: Application) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom( {
return DetailViewModel(marsProperty, application) as T
throw IllegalArgumentException("Unknown ViewModel class")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment