Skip to content

Enhancement: Add optional navGraphRoute parameter to sharedKoinViewModel for NavBackStackEntry #2261

@rfaturriza

Description

@rfaturriza

Is your feature request related to a problem? Please describe.
Currently, sharedKoinViewModel requires accessing NavBackStackEntry.destination.parent?.route internally, which limits flexibility when handling nested navigation graphs or dynamic parent graph routes.
In some cases, we need to explicitly specify a navGraphRoute different from destination.parent?.route for advanced navigation setups (e.g., shared ViewModel across sibling graphs).

Describe the solution you’d like
Introduce an overload of sharedKoinViewModel with an optional navGraphRoute parameter:

@Composable
inline fun <reified VM : ViewModel> NavBackStackEntry.sharedKoinViewModel(
    navController: NavController,
    navGraphRoute: Any? = this.destination.parent?.route,
): VM {
    val navGraphRoute = navGraphRoute ?: return koinViewModel<VM>()
    val parentEntry = remember(this) {
        navController.getBackStackEntry(navGraphRoute)
    }
    return koinViewModel(
        viewModelStoreOwner = parentEntry
    )
}

This allows developers to explicitly pass the navGraphRoute or fall back to the current default logic.

Describe alternatives you’ve considered
• Creating a custom extension in each project (current workaround, but not ideal for reusability).
• Using a wrapper function to pass route manually (less clean than built-in support).

Target Koin project
• koin-compose-viewmodel-navigation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions