I'm using Hilt, Compose, compose-navigation and I ...
# compose
c
I'm using Hilt, Compose, compose-navigation and I can't get a ViewModel to inject an object that I provide UNLESS I provide it via hiltViewModel. Is that purposeful? Code in thread.
Basically I originally had this I have
Copy code
@Composable
fun HomeScreen(
    navController: NavController,
    screenTitle: String,
    viewModel: HomeScreenViewModel = viewModel()
) {
...
}
and
Copy code
@HiltViewModel
class HomeScreenViewModel
@Inject
constructor(
    private val doSomething: Boolean,
) : ViewModel() {
...
}
and I thought this would work. It does not.
Copy code
error: viewModel has no zero argument constructor
BUT if I change it to this
Copy code
@Composable
fun HomeScreen(
    navController: NavController,
    screenTitle: String,
    viewModel: HomeScreenViewModel
) {
...
}
and then in the NavHost I do this
Copy code
composable(Screen.Home.route) {
    HomeScreen(
        navController = navController,
        screenTitle = Screen.Home.title,
        viewModel = hiltViewModel()) <------ Add this
}
then everything works.
j
the function is viewModel? isnt it hiltViewModel or viewModels? viewModel without the last S is Koin one I think
c
According to the docs here: https://developer.android.com/jetpack/compose/libraries#viewmodel I should be able to do this
Copy code
class ExampleViewModel : ViewModel() { /*...*/ }

@Composable
fun MyExample(
    viewModel: ExampleViewModel = viewModel()
) {
    // use viewModel here
}
h
AFAIK
viewModel
is the default Jetpack ViewModel which simply initializes a ViewModel using default store and provider. In that case, no external dependency should be required by the ViewModel because ViewModelProvider doesn't know how to provide it. ViewModel has to have a zero argument constructor, meaning that no dependencies. Now, you have a
HiltViewModel
which certainly knows how to provide those dependencies using Hilt. However, you have to use
hiltViewModel
function to initialize a Hilt specific ViewModel
2
c
Ah. So I need to use hiltViewModel(), but not necessarily in NavHost? I can just bake that into the composable itself? Let me try.
Okay. That worked. @Halil Ozercan thanks for rubber ducking with me. I think my main point of confusion was the "bad" error message. "viewModel has no zero argument constructor" led me down the wrong path.
👍 2
116 Views