Skip to content

Two Way Bind

paulocns edited this page Mar 14, 2019 · 2 revisions

Usage

Inside a LifeCycleOwner to perform a two way bind call the method twoWayBind

twoWayBind(queryViewModelArc.queryValue, queryEditText.bindableText)

The twoWayBind method is an extension function for LifeCycleOwner and it takes two parameters:

  • A MutableLiveData of any type
  • A TwoWayBinder of same type as the LiveData

TwoWayBinder

To add a new TwoWay binder you should add a new field as an extension function to the view that you want to be bindable.

The TwoWayBinder is an abstract class the is necessary to perform a two way binding

it has 3 methods that should be implemented:

  • oneWayBind: A method that receives a parameter as the same type as the two way bing, basically is the method that should be called when the values of the LiveData changes.

  • observeField: This method receives a WeakReference with the MutableLiveData that will be passed on the TwoWayBind method, in this method you should observe the field that you want to bind, here you set/add your listener to the view and update the value inside the mutable live data.

  • removeObserver: this method should remove any listener created on the observeField method, this is made to avoid memory leak, this is an abstract method to make sure that the listener will be removed

Clone this wiki locally