Live Data and 2-Way Data Binding: Custom setter not being called

佐手、 提交于 2019-12-03 06:49:45

Of course it's never called, you're not setting a new MutableLiveData, you're setting a new String value inside the MutableLiveData (possibly with setValue).

However, you should be able to intercept the value that's being set and execute custom logic after setting the value if you expose a MediatorLiveData instead of the MutableLiveData directly.

EDIT: the following should work as expected:

val liveReviewTitle: MutableLiveData<String> = MutableLiveData()
private val mediator = MediatorLiveData<String>().apply {
    addSource(liveReviewTitle) { value ->
        setValue(value)
        customLogicHere()
    }
}.also { it.observeForever { /* empty */ } }

@EpicPandaForce solution is proper but in EditText two way binding can be obtained in much simpler way. Add attribute afterTextChanged to your widget as below:

android:afterTextChanged="@{viewModel::doLogic}"

Then in your ViewModel class just write method:

fun doLogic(s: Editable) { //update Livedata or do other logic }

EDIT

I have missed important documentation note. Much easier (and far more proprer) will be:

android:text="@={viewModel.someLivedata}

and then in our LifecycleOwner class we can update value of liveData everywhe when we need, and of course we can react on changes from registered observer.

@EpicPandaForce is right about your setter, it's for the MutableLiveData itself and not the value it's holding. So your LiveData should be a val, no need for it to be a var, and the framework should do the right thing as long as you set a LifecycleOwner on the binding. You could add another Observer to your LiveData in place of a custom setter to add your custom logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!