I'm using Hilt with Jetpack Compose.
@HiltViewModel
class HomeViewModel @Inject constructor(
private val homeRepository: HomeRepository
): ViewModel() {
fun getCarDetails(): Car {
return homeRepository.getCarDetails()
}
}
That's how I inject the repo.
@Module
@InstallIn(SingletonComponent::class)
abstract class DataModule {
@Binds
@Singleton
abstract fun bindHomeRepository(
homeRepository: HomeRepositoryImpl,
): HomeRepository
}
And that's my composable.
@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
val carData = viewModel.getCarDetails()
Column(
Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
TopBar(carData = carData, modifier = Modifier)
CarImage(carData = carData, modifier = Modifier)
}
}
I've annotated my Activity with @AndroidEntryPoint. Can't figure out what's the problem. It crashes with a message:
java.lang.RuntimeException: Cannot create an instance of class com.example.carcontroller.ui.HomeViewModel
My library versions for compose is 1.2.1 and for hilt 2.43.2. Compose ViewModel version is 2.5.1.
EDIT: I fixed the crash and below answered how. Hope that will help someone.
Well, the developer's page isn't updated yet.
There's a library called hilt navigation compose:
implementation "androidx.hilt:hilt-navigation-compose:1.0.0"
After syncing we need to use hiltViewModel() instead of viewModel() like this
fun HomeScreen(viewModel: HomeViewModel = hiltViewModel())
Now it's not crashing. Thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With