Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1818 - Route based navigation support #1819

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
route: Int,
route: String,

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)
}