Mark Buikema
Mark Buikema

Reputation: 2540

Can I keep the original value of a LiveData in a switchMap transformation function?

I am using a ViewModel with LiveData. The code below is part of my ViewModel. It's using the switchMap transformation to get a list of items every time the searchQuery changes.

Every time searchQuery changes, the items are properly retrieved from the repository, but before the repository has returned a response, the items livedata will get a null update first, and when the repository returns a response, it updates to the correct value. Is there a way I can skip this null update and keep the original value of items until the repository actually returns a result?

val searchQuery = MutableLiveData<String>()
val items: LiveData<List<String>> = Transformations.switchMap(searchQuery) { query ->
    val liveData = MutableLiveData<List<String>>()
    launch {
        val result = itemRepository.get(query)
        liveData.postValue(result)
    }
    return liveData
}

Upvotes: 2

Views: 762

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81588

Very easy actually, you just need to ditch Transformations.switchMap { and use your own custom MediatorLiveData. Look:

val searchQuery = MutableLiveData<String>()
val items: LiveData<List<String>> = MediatorLiveData().also { mediator ->
    mediator.addSource(searchQuery) { query ->
        launch {
            val result = itemRepository.get(query)
            mediator.postValue(result)
        }
    }
}

And it should just work.

Upvotes: 5

Bam
Bam

Reputation: 530

My recommendation would be not use the LiveData as something to react to inside the ViewModel, but instead use something like BehaviorSubject to hold the latest query and be observed.

You can do something like this:

val searchQuery = BehaviorSubject.create<String>()
val items: LiveData<List<String>>

searchQuery
    .switchMap { itemRepository.get(query) }
    .subscribe( items.postValue(it) )

This way, you can

  • React to changes in query.
  • Filter on queries that are smaller then X (with .filter(...))
  • SwitchMap if another Query comes in before the first is done.
  • And post to the LiveData when you have data.

Upvotes: -2

Related Questions