Lobstw
Lobstw

Reputation: 499

How can I perform Transformations on MutableLiveData?

The docs show how you can perform Transformations on a LiveData object? How can I perform a transformation like map() and switchMap() on a MutableLiveData object instead?

Upvotes: 1

Views: 1746

Answers (2)

cutiko
cutiko

Reputation: 10527

Exactly the same way:

fun viewModelFun() = Transformations.map(mutableLiveData) {
    //do somethinf with it
}

Perhaps your problem is you dont know how does yor mutable live data fit on this. In the recent update mutable live data can start with a default value

private val form = MutableLiveData(Form.emptyForm())

That should trigger the transformation as soon as an observer is attached, because it will have a value to dispatch.

Of maybe you need to trigger it once the observer is attached

fun viewModelFun(selection: String) = liveData {
     mutableLiveData.value = selection.toUpperCase
     val source = Transformations.map(mutableLiveData) {
        //do somethinf with it
     }
     emitSource(source)
}

And if you want the switch map is usually like this:

private val name = MutableLiveData<String>()

fun observeNames() = Transformations.switchMap(name) {
        dbLiveData.search(name) //a list with the names
}

fun queryName(likeName: String) {
    name.value = likeName
}

And in the view you would set a listener to the edit text of the search

searchEt.doAfterTextChange {...
    viewModel.queryName(text)
}

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317692

MutableLiveData is just a subclass of LiveData. Any API that accepts a LiveData will also accept a MutableLiveData, and it will still behave the way you expect.

Upvotes: 1

Related Questions