Remember mutableStateOf is not working in jetcpack compose

37 Views Asked by At

I have below code to remember/rememberSaveable number on compose

var span by rememberSaveable { mutableLongStateOf(0L) }

and

someOP()
{
     span = 2
}

and when I navigate to new compose screen and back to previous screen span value is again 0

Below I'm using for navigation

navController.navigate(it.route)
{
    navController.graph.findStartDestination().id.let
    {
        route - popUpTo(route) { saveState = true }
    }
    launchSingleTop = true restoreState = true
}

if I add inclusive=true then span value is preserved however then popBackStack() does not work or navigation I have to click two times on BottomAppBarItem

1

There are 1 best solutions below

1
Leviathan On

It all works as it should.

remember is used to compensate for the side effects of recomposition. When a composable should be displayed, the function may not be only executed once, it may be executed multiple times if anything changes in that composable. That's called recomposition. But executing the same function again will forget some previously calculated state. That is where remember comes into play: It saves the remembered data from being lost during a recomposition.

Your scenario, however, is something else: By navigating to another composable the first composable leaves the composition entirely. It is wiped from memory, including all of the remembered data. After all, remember should just help you to retain state during recompositions that you, as the developer, do not care about. Navigating to another composable, however, is something you care about: You actively decided that you do not want that composable to be displayed anymore, so remember gives up, so to speak, to try to save those values. You explicitly don't care about them anymore.

You can read more about how remember works and what it is intended to do here: https://developer.android.com/jetpack/compose/state#state-in-composables

Note: remember stores objects in the Composition, and forgets the object when the composable that called remember is removed from the Composition.

What you want instead is to retain some state that survives even when the composable left the composition. That has to be done outside of the composable itself. You need to either hoist that state to another composable up in the composition tree that is unaffected by the navigation or use a ViewModel for that.