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. Wouldn't the default parameter be: NoteViewModel()?
But it works nevertheless. How is that possible?
CodePudding user response:
It is the default initializer for view models inside a 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
val vm = viewModel<MainViewModel>()
It is supposed to return the same instance of a viewmodel, if it had been created in the past.
CodePudding user response:
It works because the function viewModel()
provides that viewmodel. I assume it's from the 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.