4

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.