1

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?

Lobstw
  • 489
  • 3
  • 18

2 Answers2

1

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    I was about to vote to close this question but then I remember how poor is the doc on the subject, that is why I went with a lengthy answer – cutiko May 10 '20 at 22:56
  • @cutiko I dunno, the API docs are pretty clear the MutableLiveData is just a subclass. https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData – Doug Stevenson May 10 '20 at 23:03
  • I think the clarity is half written text and half years of experience, if OP is not even adding an example the kind thing to do is assume confusion and try to help with that, but I see your point everything is technically there. – cutiko May 10 '20 at 23:13
  • @cutiko I did think it should work out of the box, and several Google searches I made did show no one else had the same issue. But it wasn't working for my case, I will update the question shortly if appropriate – Lobstw May 10 '20 at 23:17
1

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)
}
cutiko
  • 9,887
  • 3
  • 45
  • 59