Search code examples
androidmvvmarchitectureandroid-architecture-components

How to send actions from View to ViewModel in MVVM architecture in Android


Helllo! I am working on improving my android architecture skills. I found this article which says that it is a bad practise to call viewModels functions in view.

For example calling functions in such way is a bad practice.

override fun onClick(v: View?) {
    if (v == vk_login) {
        loginViewModel.onVKLoginClick()
    }
}

I understand how to use LiveData to transfer data and actions from ViewModel to View. For this we init LiveData in view. But I can't find any information how to send user actions info using LiveData (or smth similar) from view.

Should I init LiveData in view and subscribe view model to it (Sounds strange).

Or is it better to use smth like this:

loginViewModel.nameFromUser.value = "some name from text view"

Or article which I found is just wrong and it is ok, to call viewModels functions from view?


Solution

  • A ViewModel should never include references to Android frameworks, let alone views, else it will result in a memory leak. It's better to use loginViewModel.nameFromUser.value = "some name from text view" it like this.

    DEMO

    Source - ViewModel Patterns/Anti Patterns

    A view can observer live data but the ViewModel can not observe views because the views do not emit LiveData objects.

    Quoting from the docs:

    Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context. ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners