withSetter

fun <T> LiveData<T>.withSetter(setter: (T) -> Unit): MutableLiveData<T>

Creates a MutableLiveData from LiveData by specifying the setter to use to the change the value.

This is useful in situations where a MutableLiveData is needed as an interface to modify the value (e.g., in two-way databinding with a syntax like android:checked="@={myLiveData}") but we only have a non-mutable LiveData. While sometimes it's possible to simply expose the LiveData as MutableLiveData, that may not always be possible when the source of a LiveData's value is not local.

E.g., if the LiveData merely reflects a value that actually comes from another process, the value may be changed through an asynchronous call to that other process. In this example, setter would make that asynchronous call.

Due to the nature of a setter as flexible as this, there are no guarantees as to how quickly or even if the LiveData's value will be updated as a result of setting the value on the returned MutableLiveData.