'I'm trying to implement MVVM Architecture, but this error is consuming me... (ViewModelProvider)

just it's me trying to implement MVVM architecture with Kotlin. I need to use ViewModelProvider to init my instance and I'm getting this error... Any advice?

enter image description here



Solution 1:[1]

You have a no of options to to instantiate viewmodels.

Now You can now use the ViewModelProvider constructor directly.

private val assignmentViewModel= ViewModelProvider(this).get(AssignmentViewModel::class.java)

If you use androidx.activity:activity-ktx:$Version in the library you can do this directly

private val assignmentViewModel: AssignmentViewModel by viewModels()

If you're using a viewModelFactory

private val assignmentViewModel= ViewModelProvider(this, viewModelFactory).get(AssignmentViewModel ::class.java)

and private val assignmentViewModel: AssignmentViewModel by viewModels { viewModelFactory } respectively

Solution 2:[2]

If you're using Kotlin the easiest way to incorporate a ViewModel in your code is via a property delegate:

Activity/Fragment:

    val assignmentViewModel: AssignmentViewModel by viewModels()

Fragment:

    val assignmentViewModel: AssignmentViewModel by activityViewModels()

The latter allows you to share data between fragments, since activityViewModels scopes it to the Activity.

See ViewModel Overview for more information.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 zen_of_kermit