Last active
August 11, 2019 01:53
-
-
Save alexshr/973b46abab596b1f83e1a034472b953a to your computer and use it in GitHub Desktop.
Get ViewModel scoped to this Fragment (fragment-ktx)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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