Search code examples
androidandroid-architecture-componentsandroid-livedata

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
}

Solution

  • 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.