Thread
#compose
    g

    georgiy.shur

    1 year ago
    Hello, I'm struggling a bit with using Compose + Hilt ViewModel + Navigation component together. I took this code as an inspiration and at some point I'm calling the
    viewModel
    extension, which should use the Hilt factory underneath and create my
    ViewModel
    from it. Everything works fine, but when I'm adding the Compose
    NavHost
    to the mix, the composable inside it that calls
    viewModel
    just uses the generic factory instead the one generated by Hilt. I think it has something to do with this code from the source:
    public fun NavHost(navController: NavHostController, graph: NavGraph) {
        var context = AmbientContext.current
        val lifecycleOwner = AmbientLifecycleOwner.current
        val viewModelStore = AmbientViewModelStoreOwner.current.viewModelStore
        ...
    }
    What is the right way to make them work together? I'm still not sure that I'm getting the Ambient concept right.
    I think I see the reason why it's not working. The current
    ModelStoreOwner
    normally is
    MyActivity
    , which is annotated with
    AndroidEntryPoint
    , so it knows how to inject the right view-model. But inside the
    NavHost
    composable, the current
    ModelStoreOwner
    is
    NavBackStackEntry
    , created by the framework, so it knows nothing about Hilt injection. The question stands though, how to make them work together? 🙂
    i

    Ian Lake

    1 year ago
    If you search for Hilt Navigation, you'll find a number of threads on this, such as the latest one: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1608166792382300?thread_ts=1608142991.351300&cid=CJLTWPH7S