ViewModel vs rememberSaveable

Akbolat Sadvakassov
2 min readDec 1, 2022

--

Successfully captured on https://developer.android.com/jetpack

It’s the question I asked Google, while was passing one of their trainings they’re advertising last month. It’s called Compose Camp. Where you can earn badges( the reason I attempted) and certificate.

Back to the topic. I didn’t find anything clear about it. So made a quick overview, not deep research, leaving it to someone else.

Here is the question from one of the quiz:

Sorry for the spoiler

What is rememberSaveable according to the docs:

It behaves similarly to remember, but the stored value will survive the activity or process recreation using the saved instance state mechanism (for example it happens when the screen is rotated in the Android application).

Sounds interesting, isn't it?

@Composable
fun <T : Any?> rememberSaveable(
vararg inputs: Any?,
stateSaver: Saver<T, Any>,
key: String? = null,
init: () -> MutableState<T>
): MutableState<T>

If you look closer, there is a parameter called stateSaver: Saver<T, Any> , which does the trick. The documentation says it can store almost everything you can put into Bundle, including classes with Parcelable implementation or make your own mapper to handle that.

But what about limitations? There is no info. But as it stated before that it uses the saved instance state mechanism, we can refer to that comparison:

Imaging that rememberSaveable is typed in brackets next to SavedInstanceState.

In short, it’s an alternative to onSaveInstanceState/onRestoreInstanceState from Activity/Fragment and SavedStateHandle from ViewModel. Because the first two of them are no longer available in a pure Compose app.

--

--