androidandroid-livedataandroid-architecture-componentsandroid-savedstate

How to save LiveData into saveStateHandle?


As shown in https://stackoverflow.com/a/61166665/3286489, we could save LiveData in savedStateHandle.

I could do that easily https://stackoverflow.com/a/61166665/3286489

private val textLiveData: MutableLiveData<String>

init {
    textLiveData = savedStateHandle.getLiveData(KEY)
}

However, when trying to save it as below,

savedStateHandle.set(KEY, textLiveData)

I got the error

java.lang.IllegalArgumentException: Can't put value with type class androidx.lifecycle.SavedStateHandle$SavingStateLiveData into saved state

Where did I get it wrong?


Solution

  • Apparently the better answer is, we don't even need to

    savedStateHandle.set(KEY, textLiveData.value)
    

    While that is permissible, when we one do set

    textLiveData.value = "Some data"
    

    This already saved to the state. As textLiveData is retrieved from savedStateHandle as below.

    textLiveData = savedStateHandle.getLiveData(KEY) 
    

    Hence the textLiveData is already stored within the savedStateHandle, and changes to textLiveData.value is inadvertently get saved in savedStateHandle.