Dataflow mediator for LiveData
Library ID dataflow-mediator-livedata

LiveData to Field conversion

When using Android™, you may need to handle LiveData objects: they may come from an external library such as Room, where you don't have control over which type of data is returned.

To convert them to fields this mediator offers toField(), a very easy and intuitive extension function to the LiveData class:

val liveData : LiveData<String> = getLiveData() //Obtain a LiveData object from somewhere val fld : Field<String?> = liveData.toField() //Converts the LiveData to a Field
LiveData<String> liveData = getLiveData(); //Obtain a LiveData object from somewhere Field<String> fld = DataflowLiveDataMediation.toField(liveData) //Converts the LiveData to a Field

The returned field will observe() the value changes of the LiveData and will update the Field value accordingly.

The Android Lifecycle used to observe the LiveData has the following behavior:

  • When the Field is first created, ON_CREATE is dispatched
  • When the field becomes active (has attached listeners), ON_START will be dispatched
  • When field becomes inactive (has NOT attached listeners), ON_STOP will be dispatched

Notice how the returned Field may contain null: this is necessary because the LiveData can always contain a null pointer.

Mutable variant


Similarly we can convert a MutableLiveData to a MutableField with the toMutableField() function:

val mutableLiveData : MutableLiveData<String> = getMutableLiveData() //Obtain a MutableLiveData object from somewhere val mutableField : MutableField<String?> = mutableLiveData.toMutableField() //Converts the MutableLiveData to a MutableField
MutableLiveData<String> liveData = getMutableLiveData(); //Obtain a MutableLiveData object from somewhere MutableField<String> field = DataflowLiveDataMediation.toMutableField(mutableLiveData) //Converts the MutableLiveData to a MutableField

Whenever the returned MutableField value is changed, the original MutableLiveData value will be updated accordingly using the postValue() function.