One Off the Slack: When Do We Use rememberSaveable()?

Marko Novakovic asked:

remember {} saves X for recomposition but when composable leaves the screen X is forgotten. if I want to save X even when composable leaves the screen I should use rememberSaveable {} right? it seems weird because concept of rememberSaveable {} is for surviving recreating but composable leaving the screen is not recreation. conceptually not the same. should I use rememberSaveable {} or there is some other way to handle this use case? (edited)

knthmn suggested state hoisting, where you track the state at the highest necessary point in your composable hierarchy. Marko countered:

I understand and I agree. BUT. what if you don’t need/want that state hoisted? let’s say you have list of items you want to select. yes, you probably need to do something with those items inside ViewModel or something and in that case you can make composables(items) in the list stateless (implementation differs from use case to use case) but what if you don’t need these items inside ViewModel? maybe your use case is so simple and you would introduce ViewModel just for saving checked state? this is all maybe and probably not good example but I hope you get a point

Other discussion indicated that Marko’s scenario centered around a LazyColumn(), where state was lost when rows scrolled off the screen.

Google’s Adam Powell pointed out:

all the viewModel composable is doing is hoisting your state into LocalViewModelStoreOwner.current for you

the lazy layouts do indeed have items leave the composition entirely when they’re no longer visible, so yes, if you don’t hoist state somewhere, it won’t stick around.

Google’s Andrey Kulikov indicated that rememberSaveable() is a reasonable choice here:

rememberSaveable can also be used inside LazyColumn items for not loosing the local state when the item is scrolled off the screen(for example for checked state as you mentioned). so activity recreation is just one of the use cases of rememberSaveable

Personally, that makes me nervous, as I worry that we are now saving state well outside its necessary scope. But, I have not rummaged through the implementation of rememberSaveable(), and perhaps it is safer than I am imagining. The fact that Andrey recommended it, and Adam did not counter, suggests that indeed perhaps this is an acceptable pattern.


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!