Skip to content

Instantly share code, notes, and snippets.

@adam-hurwitz
Last active September 4, 2020 20:13
Show Gist options
  • Select an option

  • Save adam-hurwitz/37e22ee6d8f1c7a74ab15d26a377d9b2 to your computer and use it in GitHub Desktop.

Select an option

Save adam-hurwitz/37e22ee6d8f1c7a74ab15d26a377d9b2 to your computer and use it in GitHub Desktop.
Optimizing ViewModel with Lifecycle 2.2.0: Passing Arguments/Parameters
// Override ViewModelProvider.NewInstanceFactory to create ViewModel (VM)
class CustomViewModelFactory(private val someString: String): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = SomeViewModel(someString) as T
}
class Fragment: Fragment() {
// Create VM in activity/fragment with VM factory.
val feedViewModel: FeedViewModel by viewModels { CustomViewModelFactory("someString") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment