Skip to content

Instantly share code, notes, and snippets.

@igorwojda
Last active January 7, 2019 19:28
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 igorwojda/b517778d778653c889f77c3d42ef0aa3 to your computer and use it in GitHub Desktop.
Save igorwojda/b517778d778653c889f77c3d42ef0aa3 to your computer and use it in GitHub Desktop.
Fragment withViewModel
inline fun <reified T : ViewModel> Fragment.withViewModel(
crossinline factory: () -> T,
body: T.() -> Unit
): T = getViewModel(factory).also { it.body() }
inline fun <reified T : ViewModel> Fragment.getViewModel(crossinline factory: () -> T): T {
val vmFactory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <U : ViewModel> create(modelClass: Class<U>): U = factory() as U
}
return ViewModelProviders.of(this, vmFactory)[T::class.java]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment