So in order to retain state across activity recrea...
# compose
a
So in order to retain state across activity recreation (activity process death and restoration)
state
would need to be store in
Copy code
var someState by savedInstanceState<String?> { ... }
but what if the state is inside a
LiveData
and is accessed as
Copy code
var liveDataState by liveData.observeState()
How could I put this
liveDataState
inside
savedInstanceState
?
đź‘€ 1
z
Whatever owns the
LiveData
should be responsible for saving/restoring its internal state in that case. Otherwise, you’ve got two sources of truth.
âž• 3
a
hmmm... I'm sorry I'm so confuse. I still don't know what to do. Does that mean doing?
Copy code
var liveDataState by liveData.observeState()
var someState by savedInstanceState { liveDataState }

SomeView(someState)
I'm really sorry about this.
m
I think what he’s saying is that something is creating the “liveData” object. Whatever is creating that needs to have access to the SavedStateHandle so that whenever the value is written, the SavedStateHandle is updated.
SavedStateHandle has a function to do this for you: savedStateHandle.getLiveData(key)
if you’re unfamiliar with the saved state library, i suggest you read up on that, and this will make sense.
a
Yes that is true and would work really well with
LiveData
but how about
Flow
or
Rx
?
In this case is it correct to do:
Copy code
class MyViewModel(
    val savedStateHandle: SaveStateHandle
): ViewModel {

    private val myMutableFlow = MutableStateFlow<String>("")
    val flow: StateFlow<String> = myMutableFlow

    private savedStateLiveData = savedStateHandle.getLiveData("MyKey")

    init {
        savedStateLiveData.observeForever { savedValue ->
            myMutableFlow.value = savedValue
        }
    }

    ....

    override onCleared() {
        savedStateLiveData.removeObservers()
    }

}