0

What does the following line of code do?

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cluster1
  • 4,968
  • 6
  • 32
  • 49

2 Answers2

2

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.

Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42
  • Your answer with the default initializer makes sense to me. I guess in the case, I have shown, it takes the type-hint from "noteViewModel: NoteViewModel". Means: The "... : NoteViewModel ..." might be equivalent to . – cluster1 Aug 24 '22 at 07:12
1

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.

Stephan
  • 15,704
  • 7
  • 48
  • 63