Created
September 30, 2020 12:51
-
-
Save robotsquidward/b61f2389059876b6d1a7e7195f6a009d to your computer and use it in GitHub Desktop.
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
/** | |
* 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