Last active
January 7, 2019 19:28
-
-
Save igorwojda/b517778d778653c889f77c3d42ef0aa3 to your computer and use it in GitHub Desktop.
Fragment withViewModel
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
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