Skip to content

Instantly share code, notes, and snippets.

@DJDarkByte
Last active August 3, 2020 08:54
Show Gist options
  • Save DJDarkByte/67a44b034bbf05a9fb7d95ed1139239d to your computer and use it in GitHub Desktop.
Save DJDarkByte/67a44b034bbf05a9fb7d95ed1139239d to your computer and use it in GitHub Desktop.
NavGraph scoped ViewModel with SavedStateHandle
Extension function:
fun <VM : ViewModel> Fragment.stateNavGraphViewModel(
clazz: KClass<VM>,
@IdRes navGraphId: Int,
qualifier: Qualifier? = null,
bundle: Bundle? = null,
parameters: ParametersDefinition? = null
) = lazy {
val owner = findNavController().getViewModelStoreOwner(navGraphId)
getKoin().getViewModel(ViewModelParameter(
clazz,
qualifier,
parameters,
bundle ?: Bundle(),
owner.viewModelStore,
this)
)
}
Definition in Koin Module:
viewModel { (handle: SavedStateHandle) -> ScopeViewModel(handle, get()) }
Usage in scoped fragments in navGraph scope:
val viewModel: ScopeViewModel by stateNavGraphViewModel(clazz, navGraphId)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment