For anyone trying to use compose and hilt to injec...
# compose
a
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
Copy code
NavHost(navController = navController, startDestination = "splash") {
            composable("splash") {
                SplashScreen(navController)
            }
            composable("home") {
                HomeScreen()
            }
        }
and you SplashScreen was defined somewhat like this
Copy code
@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
Copy code
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
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
🙌 4