diff --git a/docs/reference/koin-android/viewmodel.md b/docs/reference/koin-android/viewmodel.md index 931bbd9f7..aa5fdbd12 100644 --- a/docs/reference/koin-android/viewmodel.md +++ b/docs/reference/koin-android/viewmodel.md @@ -165,12 +165,13 @@ All `stateViewModel` functions are deprecated. You can just use the regular `vie ## Navigation Graph ViewModel -You can scope a ViewModel instance to your Navigation graph. Just retrieve with `by koinNavGraphViewModel()`. You just need your graph id. +You can scope a ViewModel instance to your Navigation graph. Just retrieve with `by koinNavGraphViewModel()`. You need either your graph id or graph route. ```kotlin class NavFragment : Fragment() { - val mainViewModel: NavViewModel by koinNavGraphViewModel(R.id.my_graph) + val mainViewModel: NavViewModel by koinNavGraphViewModel(R.id.my_graph) // id based + val secondaryViewModel: NavViewModel by koinNavGraphViewModel("my_graph_route") // route based } ``` diff --git a/projects/android/koin-androidx-navigation/src/main/java/org/koin/androidx/navigation/NavGraphExt.kt b/projects/android/koin-androidx-navigation/src/main/java/org/koin/androidx/navigation/NavGraphExt.kt index 8d9be8429..7308a8887 100644 --- a/projects/android/koin-androidx-navigation/src/main/java/org/koin/androidx/navigation/NavGraphExt.kt +++ b/projects/android/koin-androidx-navigation/src/main/java/org/koin/androidx/navigation/NavGraphExt.kt @@ -41,3 +41,20 @@ inline fun Fragment.koinNavGraphViewModel( ): Lazy { return viewModel(qualifier, ownerProducer, extrasProducer, parameters) } + +/** + * Request a ViewModel instance, scoped to Navigation graph + * + * @param route + * + * @author Sebastian Helzer + */ +inline fun Fragment.koinNavGraphViewModel( + route: Int, + qualifier: Qualifier? = null, + noinline ownerProducer: () -> ViewModelStoreOwner = { findNavController().getBackStackEntry(route) }, + noinline extrasProducer: (() -> CreationExtras)? = null, + noinline parameters: (() -> ParametersHolder)? = null, +): Lazy { + return viewModel(qualifier, ownerProducer, extrasProducer, parameters) +}