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.