简体   繁体   English

Jetpack Compose 和 ViewModel-Instantiation

[英]Jetpack Compose and ViewModel-Instantiation

Can someone explain me this line of code:有人可以解释一下这行代码:

fun NotesApp(noteViewModel: NoteViewModel = viewModel()) {

The default parameter confuses me.默认参数让我感到困惑。 The class, which inherits from ViewModel, is called NoteViewModel.继承自 ViewModel 的 class 称为 NoteViewModel。 Wouldn't the default parameter be: NoteViewModel()?默认参数不会是:NoteViewModel()?

But it works nevertheless.但它仍然有效。 How is that possible?这怎么可能?

It is the default initializer for view models inside a Composable.它是 Composable 中视图模型的默认初始化器。 It takes in a type parameter, so I don't think what you've posted above would be enough.它接受一个类型参数,所以我认为您在上面发布的内容还不够。

For example, if you wanted to initialise a MainViewModel , it'll be something like例如,如果你想初始化一个MainViewModel ,它会是这样的

val vm = viewModel<MainViewModel>()

It is supposed to return the same instance of a viewmodel, of it had been created in the past.它应该返回视图模型的相同实例,它是在过去创建的。

It works because the function viewModel() provides that viewmodel.它之所以有效,是因为 function viewModel()提供了该视图模型。 I assume it's from the androidx.lifecycle.viewmodel.compose package.我假设它来自androidx.lifecycle.viewmodel.compose package。

Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.返回现有 ViewModel 或在给定所有者(通常是片段或活动)中创建新视图模型,默认为 LocalViewModelStoreOwner 提供的所有者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM