https://kotlinlang.org logo
#compose
Title
# compose
t

Tlaster

10/30/2020, 7:30 AM
Hi. I'm using compose and compose-navigation with hilt injecting my viewModel, but I got
RuntimeException: Cannot create an instance of class MyViewModel
. Does anyone have the same issue?
👍 3
j

jannis

10/30/2020, 8:27 AM
I’m using the same with the latest versions and I don’t get any errors. Does your ViewModel have a public constructor? Did you annotate your Activity/Fragment with
@AndroidEntryPoint
?
Or does your ViewModel have parameters and you don’t use a Factory?
t

Tlaster

10/30/2020, 8:31 AM
Thanks, it works fine when not using
NavHost
from the new navigation-compose package.
j

jannis

10/30/2020, 8:34 AM
Where exactly do you want to use it and how did you add it?
Works fine for me within a
NavHost
t

Tlaster

10/30/2020, 8:40 AM
I here is my activity's onCreate
Copy code
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        val navController = rememberNavController()
        NavHost(
            navController = navController,
            startDestination = "home",
            builder = {
                composable("home") {
                    HomeScene()
                }
            }
        )
    }
}
and HomeScene is
Copy code
@Composable
fun HomeScene() {
    val viewModel = viewModel<HomeViewModel>()
    Scaffold {
        Column(
            modifier = Modifier.fillMaxWidth().fillMaxHeight(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(vectorResource(id = R.drawable.ic_launcher_foreground))
        }
    }
}
and HomeViewModel is
Copy code
class HomeViewModel @ViewModelInject constructor(
    private val repository: MyRepository
) : ViewModel() {
    fun myAccount() = repository.myAccount()
}
j

jannis

10/30/2020, 9:21 AM
Ah. I’m injecting my viewModel manually atm (not using
@ViewModelInject
) 😞
t

Tlaster

10/30/2020, 9:23 AM
Thanks! I'll try injecting manually since
@ViewModelInject
not working atm.
a

allan.conda

10/30/2020, 10:07 AM
good to know, I might encounter same issue later
could you file a bug report? That would be helpful
i

Ian Lake

10/30/2020, 3:27 PM
The Hilt docs explain what you need to do when using Navigation+Hilt ViewModels: https://developer.android.com/training/dependency-injection/hilt-jetpack#viewmodel-navigation
That would apply to any
viewModel()
calls within a
NavHost
t

Tlaster

10/31/2020, 6:32 AM
Thanks! Now it works by passing
defaultViewModelProviderFactory
to
viewModel()