Skip to content

Instantly share code, notes, and snippets.

@robotsquidward
Created September 30, 2020 12:51
Show Gist options
  • Save robotsquidward/b61f2389059876b6d1a7e7195f6a009d to your computer and use it in GitHub Desktop.
Save robotsquidward/b61f2389059876b6d1a7e7195f6a009d to your computer and use it in GitHub Desktop.
/**
* Get a [ViewModel] in an [ComponentActivity].
*/
@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.viewModelBuilder(
noinline viewModelInitializer: () -> VM
): Lazy<VM> {
return ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { viewModelStore },
factoryProducer = {
return@ViewModelLazy object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")// Casting T as ViewModel
return viewModelInitializer.invoke() as T
}
}
}
)
}
/**
* Get a [ViewModel] in a [Fragment].
*/
@MainThread
inline fun <reified VM : ViewModel> Fragment.activityViewModelBuilder(
noinline viewModelInitializer: () -> VM
): Lazy<VM> {
return ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { requireActivity().viewModelStore },
factoryProducer = {
object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")// Casting T as ViewModel
return viewModelInitializer.invoke() as T
}
}
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment