Learning Android Development

Saving StateFlow State in ViewModel

Ensure your state flow value persist through process death

Photo by Rinck Content Studio on Unsplash

Not too long ago, Google introduced an article on how one can migrate from LiveData to StateFlow. A great read.

However, there’s no mention of how can one persist the StateFlow value across process death. Hence, here I explore the way to do so.

Manually Save and Retrieve the Value

For a normal flow, we can convert to StateFlow that is equivalent to LiveData as below.

val stateFlow = flow {
emit(suspendFunc())
}.stateIn(
scope = viewModelScope + Dispatchers.IO,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = "Nothing"
)

This, however, means that whenever we start observing from it, it will start reading from suspendFunc() again, i.e. if the process kill the app, then all will start again.

--

--