a

    Abhishek Dewan

    1 year ago
    For anyone trying to use compose and hilt to inject viewModels along with compose nav host composable, here is a github issue to be aware of https://github.com/google/dagger/issues/2166#issuecomment-769162910. In short, if you have a navHost that defines routes then viewModel inject stops working in those routes. For e.g
    NavHost(navController = navController, startDestination = "splash") {
                composable("splash") {
                    SplashScreen(navController)
                }
                composable("home") {
                    HomeScreen()
                }
            }
    and you SplashScreen was defined somewhat like this
    @Composable
    fun SplashScreen(navController: NavHostController) {
        
        val viewModel: SplashViewModel = viewModel()
    The injection will not work if your SplashScreenViewModel takes non zero constructor params. In order to fix this you need to inject the viewModel somewhat like this
    val viewModel: SplashViewModel = viewModel(
            factory = HiltViewModelFactory(
                LocalContext.current,
                navController.getBackStackEntry("splash")
            )
        )
    and this is possible by using the
    androidx.hilt:hilt-navigation:1.0.0-alpha03
    library. I spent the last hour trying to debug why despite everything being right, the injection wouldn’t work 😄
    i

    Ian Lake

    1 year ago
    Using Hilt with Navigation Compose should be even easier later this week (if all goes according to plan): https://kotlinlang.slack.com/archives/CJLTWPH7S/p1614619457323100?thread_ts=1614601227.289300&cid=CJLTWPH7S