In VIew how to use ViewModel with ViewModelProvider

315 Views Asked by At

Here is my MineSweeperView class:

class MineSweeperView : View {

constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    private var userViewModel: UserViewModel


    init {
        ....
        userViewModel = ViewModelProvider(???).get(UserViewModel::class.java)
    }

ViewModelProvider(this) and (context) is not working in View class.

1

There are 1 best solutions below

0
On

You can't do this. It would be improper for a View to have a ViewModel class. ViewModels are only for LifecycleOwners, because they are scoped to the life of a LifecycleOwner. That's the whole reason for the existence of ViewModel, to have it's life controlled by the life of some other lifecycle object.