Skip to content

Instantly share code, notes, and snippets.

@Guang1234567
Created January 4, 2023 07:21
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 Guang1234567/3be582daab6bb5a5a49b9d6f86a89b0e to your computer and use it in GitHub Desktop.
Save Guang1234567/3be582daab6bb5a5a49b9d6f86a89b0e to your computer and use it in GitHub Desktop.
findViewTreeViewModelStoreOwner findViewTreeLifecycleOwner findViewTreeSavedStateRegistryOwner
private inline fun <reified VM : ViewModel> View.underViewMode(
savedStateDefaultArgs: Bundle? = null,
crossinline viewModelCreator: (
savedStateHandle: SavedStateHandle,
outerLifecycle: Lifecycle,
outerLifecycleScope: CoroutineScope
) -> VM,
block: VM.(
outerLifecycle: Lifecycle,
outerLifecycleScope: CoroutineScope
) -> Unit
) {
findViewTreeViewModelStoreOwner()?.let { viewModelStoreOwner ->
findViewTreeLifecycleOwner()?.let { lifecycleOwner ->
findViewTreeSavedStateRegistryOwner()?.let { savedStateRegistryOwner ->
val viewModel: VM = ViewModelProvider(
viewModelStoreOwner,
object :
AbstractSavedStateViewModelFactory(
savedStateRegistryOwner,
savedStateDefaultArgs ?: bundleOf()
) {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
return viewModelCreator(
handle,
lifecycleOwner.lifecycle,
lifecycleOwner.lifecycleScope
) as T
}
}
).get()
viewModel.block(
lifecycleOwner.lifecycle,
lifecycleOwner.lifecycleScope
)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment