当我使用 Compose 时,如何使用 Hilt 自动实例化 ViewModel class?

How to instance a ViewModel class automatically with Hilt when I use Compose?

代码A来自官方样本的末尾分支project.

项目使用Hilt实现依赖注入

在我看来,当我使用Hilt时,我不需要手动实例化一个ViewModel class,系统会自动实例化一个ViewModel需要的时候。

但是好像作者在代码A中用代码viewModel: MainViewModel = viewModel()手动实例化了ViewModelclass,我怎么实例化一个ViewModeclass 当我使用 Compose 时自动使用 Hilt?

代码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() {

   ...
}

documentation

中所述

The viewModel() function mentioned in the ViewModel section automatically uses the ViewModel that Hilt constructs with the @HiltViewModel annotation. We've provided documentation with information about Hilt's ViewModel integration.

因此,只要您的视图模型具有 @HiltViewModel 注释,您就无需进行任何更改。

正如@Karim0x1 所说。 Official Android Developer Documentation 像这样指导我们:

The viewModel() function mentioned in the ViewModel section automatically uses the ViewModel that Hilt constructs with the @HiltViewModel annotation. We've provided documentation with information about Hilt's ViewModel integration.

@HiltViewModel
class ExampleViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle,
    private val repository: ExampleRepository
) : ViewModel() { /* ... */ }

@Composable
fun ExampleScreen(
    exampleViewModel: ExampleViewModel = viewModel()
) { /* ... */ }