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

Time:03-26

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related