Skip to content

Instantly share code, notes, and snippets.

@alexshr
Last active August 11, 2019 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexshr/973b46abab596b1f83e1a034472b953a to your computer and use it in GitHub Desktop.
Save alexshr/973b46abab596b1f83e1a034472b953a to your computer and use it in GitHub Desktop.
Get ViewModel scoped to this Fragment (fragment-ktx)
//my sample
//https://github.com/alexshr/android-kotlin-fundamentals-apps/tree/master/MarsRealEstateFinal
//doc
//https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels
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 {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DetailViewModel::class.java)) {
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