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

Rafael Costa

05/04/2022, 7:05 PM
Sometimes
remember
saved state is lost after screen is turned off and on. 🧵
I have this code:
Copy code
var things by remember { mutableStateOf("") }
        TextField(
            value = things,
            onValueChange = { things = it }
        )
as part of a screen that is registered in compose navigation.
when I turn screen off and on, sometimes the text field goes back to empty string, other times it doesnt.
I added a lifecycle observer to NavBackStackEntry and I found this:
Copy code
WHEN STATE IS LOST:
onStateChanged NavBackStackEntry@86ef65fd - ON_PAUSE
onStateChanged NavBackStackEntry@86ef65fd - ON_STOP <-- Screen turn off
onStateChanged NavBackStackEntry@86ef65fd - ON_CREATE <-- Screen turn on and text field state is lost
onStateChanged NavBackStackEntry@86ef65fd - ON_START
onStateChanged NavBackStackEntry@86ef65fd - ON_RESUME


WHEN STATE IS KEPT:
onStateChanged NavBackStackEntry@5be23c59 - ON_PAUSE
onStateChanged NavBackStackEntry@5be23c59 - ON_STOP <-- Screen turn off
onStateChanged NavBackStackEntry@5be23c59 - ON_START <-- Screen turn on and text field state is kept
onStateChanged NavBackStackEntry@5be23c59 - ON_RESUME
Is this expected?
If I call the composable directly, i.e without using navigation code, it doesn’t seem to happen. @Ian Lake any idea?
(sorry to call you directly 🙏 )
i

Ian Lake

05/04/2022, 7:22 PM
If you want your state saved, you'd want to use
rememberSaveable
.
r

Rafael Costa

05/04/2022, 7:24 PM
Got it yeah, I tried and that works indeed. I was just confirming that this was expected. It's kinda weird that it just happens when in a composable registered as a destination in NavHost
Anyway, thanks for quick reply. I will pass this feedback to the person that actually asked me
2 Views