How can we combine SavedStateHandler with LiveData Coroutine Builder?

129 Views Asked by At

In a typical Android ViewModel, we can easily create a Restorable LiveData using

val liveData = savedStateHandle.getLiveData<String>("SomeKey")

Whenever the liveData value is set, it is automatically saved and restorable

However, if we use the liveData coroutine builder (i.e. https://developer.android.com/topic/libraries/architecture/coroutines#livedata)

val liveDataSaved: LiveData<String> = liveData {
    emit(someValue)
}

How can we also join it with savedStateHandle? (e.g. when restoring, it will first retrieved the previous emitted value instead of reinitialize)

Note: I can do as below, just look hacky.

val liveDataSaved: LiveData<String> = liveData {
    val someValue = savedStateHandle.get("Key") ?: getValue()
    savedStateHandle.put("Key", someValue)
    emit(someValue)
}
1

There are 1 best solutions below

0
Jeel Vankhede On

You can use MediatorLiveData to combine multiple other live data sources and then observe on this resulting MediatorLiveData at the end.

In your case, you can have multiple sources to this MediatorLiveData something like below:

val liveDataValue = MediatorLiveData<String>().apply {
    var intermediateValue = ""

    fun update() {
        this.value = intermediateValue
    }

    addSource(savedStateHandle.getLiveData<String>("SomeKey")) {
        intermediateValue = it
        update()
    }

    addSource(
        liveData {
            emit(someValue)
        }
    ) {
        intermediateValue = it
        update()
    }
}