anon37894203
anon37894203

Reputation: 545

Kotlin by viewModels not working with 2 way data binding

I am using Android MVVM pattern and two way data binding in my application. I have a simple form with some MutableLiveData of string, and then a MediatorLiveData of boolean which checks if all fields are filled and enables or disables the button:

var name = MutableLiveData<String>()
var id = MutableLiveData<String>()
...
var isValid = MediatorLiveData<Boolean>()

I am of course adding the sources to the MediatorLiveData.

My problem is that I'm initializing the viewmodel like this in my fragment:

private val viewModel: StudentViewModel by viewModels()

And since I'm not calling the viewmodel in my fragment code, this is not working:

<layout>
<data>
<variable name="viewModel" type="com.example.app.viewmodels.StudentViewModel"/>
</data>
...
<FloatingActionButton ...
android:enabled="@{viewModel.isValid}"

Before I was using Java and this worked, but I switched to Kotlin and I do not want to make the viewModel nullable and initialize it onCreate. Shouldn't this work out of the box or I am doing something wrong?

My StudentViewModel init method is not being called, nor the validation method of the MediatorLiveData. Of course the button is only one way binding since two way binding does not make sense on the enabled attribute of a button. The fields are two-way bind.

Upvotes: 2

Views: 1122

Answers (1)

You need to assign the lifecycle owner of the viewModel:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = YourBinding.bind(view)
        binding.apply {
            viewModel = mViewModel
            lifecycleOwner = viewLifecycleOwner
        }
    }

Where mViewModel is the variable you lazy initialized.

Upvotes: 1

Related Questions