Skip to content

Commit

Permalink
Route based navigation support
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastianHelzer committed Mar 11, 2024
1 parent 0dcf904 commit 869a2ea
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions docs/reference/koin-android/viewmodel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

}
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,20 @@ inline fun <reified VM : ViewModel> Fragment.koinNavGraphViewModel(
): Lazy<VM> {
return viewModel(qualifier, ownerProducer, extrasProducer, parameters)
}

/**
* Request a ViewModel instance, scoped to Navigation graph
*
* @param route
*
* @author Sebastian Helzer
*/
inline fun <reified VM : ViewModel> Fragment.koinNavGraphViewModel(
route: Int,
qualifier: Qualifier? = null,
noinline ownerProducer: () -> ViewModelStoreOwner = { findNavController().getBackStackEntry(route) },
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline parameters: (() -> ParametersHolder)? = null,
): Lazy<VM> {
return viewModel(qualifier, ownerProducer, extrasProducer, parameters)
}

0 comments on commit 869a2ea

Please sign in to comment.