Skip to content

Instantly share code, notes, and snippets.

@thats-bot
Created January 7, 2021 16:05
Show Gist options
  • Save thats-bot/1bec024bc187b1afc8e583dd3336952b to your computer and use it in GitHub Desktop.
Save thats-bot/1bec024bc187b1afc8e583dd3336952b to your computer and use it in GitHub Desktop.
Koin implementation of sharedGraphViewModel with ability to use SavedStateHandle functional inside ViewModel
/**
* Usage:
* val viewModel by sharedGraphViewModel<CheckoutViewModel>(R.id.navigationCheckout)
*/
inline fun <reified VM : ViewModel> Fragment.sharedGraphViewModel(
@IdRes navGraphId: Int,
qualifier: Qualifier? = null,
noinline initialState: BundleDefinition = { Bundle() },
noinline parameters: ParametersDefinition? = null,
) = lazy(LazyThreadSafetyMode.NONE) {
getKoin().getViewModel(
qualifier = qualifier,
state = initialState,
owner = {
val storeOwner = findNavController().getViewModelStoreOwner(navGraphId)
ViewModelOwner.from(storeOwner, storeOwner as? SavedStateRegistryOwner)
},
clazz = VM::class,
parameters = parameters
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment