Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make EditText observe a ViewModel's LiveData and forward user input to the ViewModel without using data binding

I'm trying to come up with a way to have an EditText update the data of a ViewModel and simultaneously observe that data for any changes (e.g. changes brought about by manipulating the DB). Is there a way to do this without using the data binding library?

The main problem I'm facing while simply using MutableLiveData is the following:

when the user enters text in the EditText, a TextWatcher pokes the ViewModel to update its data, which in turn will set the new text to the MutableLiveData object. Because the EditText is observing the LiveData, the onChange is triggered and sets the text of the EditText accordingly, which in turn will trigger the TextWatcher again creating an infinite loop.

like image 940
kazume Avatar asked Sep 26 '18 11:09

kazume


1 Answers

I also ran into this problem since I don't like the databinding library. I did as @kAliert said, but in my ViewModel to keep the logic there. I just added a simple catch on the function that receives my text changes events in the ViewModel. It works well.

fun editTextChanged(newText: String) {
    if (newText == textLiveData.value) {
        return
    }
}
like image 123
Carson Holzheimer Avatar answered Oct 11 '22 13:10

Carson Holzheimer