Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hasanmohdkhan/08230354e8475812720e27022bfe6474 to your computer and use it in GitHub Desktop.
Save hasanmohdkhan/08230354e8475812720e27022bfe6474 to your computer and use it in GitHub Desktop.
Optimizing ViewModel with Lifecycle 2.2.0: Passing Arguments/Parameters
// Override ViewModelProvider.NewInstanceFactory to create the ViewModel (VM).
class SomeViewModelFactory(private val someString: String): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = SomeViewModel(someString) as T
}
class SomeViewModel(private val someString: String) : ViewModel() {
init {
//TODO: Use 'someString' to init process when VM is created. i.e. Get data request.
}
}
class Fragment: Fragment() {
// Create VM in activity/fragment with VM factory.
// Don't forget to add 'kotlinOptions { jvmTarget = '1.8' } to build.gradle (:app)'
val someViewModel: SomeViewModel by viewModels { SomeViewModelFactory("someString") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment