karenkovigor
10/18/2022, 11:06 AMrememberSaveable
inside SaveableStateHolder.SaveableStateProvider
: rememberSaveable loses data when composable hierarchy changes. I provided the example to reproduce behavior which contains either correct and incorrect version, but if you use both composables simultaneously, correct version brakes.Albert Chang
10/18/2022, 11:47 AM@param key An optional key to be used as a key for the saved value. If not provided we use the automatically generated by the Compose runtime which is unique for the every exact code location in the composition treeThe default keys will be different for separated invocations. If you want to restore the same value, you should provide the same
key
manually.karenkovigor
10/18/2022, 11:52 AMrememberSaveable
is called inside SaveableStateProvider
and I’ve already provided key for SaveableStateProvider
.karenkovigor
10/18/2022, 11:52 AM/**
* Allows to save the state defined with [rememberSaveable] for the subtree before disposing it
* to make it possible to compose it back next time with the restored state. It allows different
* navigation patterns to keep the ui state like scroll position for the currently not composed
* screens from the backstack.
*
* @sample androidx.compose.runtime.saveable.samples.SimpleNavigationWithSaveableStateSample
*
* The content should be composed using [SaveableStateProvider] while providing a key representing
* this content. Next time [SaveableStateProvider] will be used with the same key its state will be
* restored.
*/
interface SaveableStateHolder {
/**
* Put your content associated with a [key] inside the [content]. This will automatically
* save all the states defined with [rememberSaveable] before disposing the content and will
* restore the states when you compose with this key again.
*
* @param key to be used for saving and restoring the states for the subtree. Note that on
* Android you can only use types which can be stored inside the Bundle.
*/
@Composable
fun SaveableStateProvider(key: Any, content: @Composable () -> Unit)
Albert Chang
10/18/2022, 11:56 AMunique for the every exact code location in the composition treeIt maybe a little bit hard to understand but the
ScreenContent
calls are different so they are not in the same location in the composition tree.
And I mean provide a key
for rememberSaveable
.karenkovigor
10/18/2022, 11:56 AMval background = rememberSaveable(key = id) { Random.nextInt() }
Albert Chang
10/18/2022, 11:57 AMAndrey Kulikov
10/19/2022, 12:54 PMkarenkovigor
10/19/2022, 1:26 PMSaveableStateProvider
(which provides some composition local under the hood), but not from placement in hierarchy. Documentation says
* The content should be composed using [SaveableStateProvider] while providing a key representing
* this content. Next time [SaveableStateProvider] will be used with the same key its state will be
* restored.
Andrey Kulikov
10/19/2022, 1:31 PMAndrey Kulikov
10/19/2022, 1:31 PM