HelloCW
HelloCW

Reputation: 2255

Why can't the ViewModel object be created automatically when I use Hilt as Dependency Injection in Jetpack Compose?

The following Code A is from the official sample project.

The project use Hilt as Dependency Injection.

In my mind, I needn't create the ViewModel object by myself because Hilt will create it automatically.

But in Code A, it seems that viewModel: MainViewModel = viewModel() must be created manually, why?

Code A

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun CraneHomeContent(
    onExploreItemClicked: OnExploreItemClicked,
    openDrawer: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: MainViewModel = viewModel(),
) {

   ...
}



@HiltViewModel
class MainViewModel @Inject constructor(
    private val destinationsRepository: DestinationsRepository,
    @DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher
) : ViewModel() {

   ...
}


@HiltAndroidApp
class CraneApplication : Application()

Upvotes: 1

Views: 503

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 87794

By creating manually, I mean calling the view model constructor. And this is not practiced with Hilt, because you have to pass down all the injections.

You can't just declare the viewModel: MainViewModel parameter, because then you have to pass it from the calling view.

The viewModel() does all the injection magic for you. Also, if the view model already exists, the same object will be returned. So it's completely automatic.

Upvotes: 3

Related Questions