https://kotlinlang.org logo
#compose
Title
# compose
j

JulianK

09/07/2020, 3:16 PM
Is there a solution for remembering UI State through app navigation? For example, i have a Tab Navigation/Pager with dynamic number of pages. Each page is a scrollable list containing items. When i navigate to a "sub-view" (would have been a fragment before), i'd like to remember scroll state, so when the user goes back, the list maintains it's scroll position. Remember does not work here because the component is removed from tree. Also i can't pull remember up the tree, because its not a static number of pages/lists.
t

Timo Drick

09/08/2020, 8:35 AM
I do implemented a solution to save states in my navigation framework. But you could adapt it for your needs. The interesting part is this code:
Copy code
key(item.data) {
    log("${item.data} saved state: $${item.savedState}")
    val restoredRegistry by remember(item.savedState) {
        log("${item.data} Create new registry with: ${item.savedState}")
        mutableStateOf(UiSavedStateRegistry(restoredValues = item.savedState, canBeSaved = { true }))
    }
    Providers(UiSavedStateRegistryAmbient provides restoredRegistry) {
        log("${item.data} ${UiSavedStateRegistryAmbient.current}")
        children(item.data)
        onDispose {
            val saved = restoredRegistry.performSave()
            log("${item.data} onDispose saved: $saved")
            item.savedState = saved
        }
    }
}
https://gitlab.com/timod/compose-playground/-/blob/master/app/src/main/java/com/example/composeplayground/MainActivity.kt
j

JulianK

09/08/2020, 12:47 PM
Thanks, i will look into it. I guess i was hesitating to pull the state of some deep view all the way up to my main screen in order to save tab index and/or scrolling position...
t

Timo Drick

09/08/2020, 2:21 PM
I think the upcoming official routing solution will do it more or less the same way.