1

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)
}
Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

0

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()
    }
}
Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58