I have this compose state ```val imageIndex = prod...
# compose
v
I have this compose state
Copy code
val imageIndex = produceState(0) {
    if (images.size == 1) return@produceState
    while (true) {
        delay(interval.toLong())
        value = (value + 1) % images.size
    }
}
It works fine, but if I navigate to some other screen and come back, the value resets to 0 I'm using decompose for navigation Any idea whats the problem here? If I add this line, it works but some indexes are skipped
Copy code
val index = rememberSaveable(imageIndex.value) { imageIndex.value }
using this fixes the problem, but should I be using rememberSaveable???
Copy code
val imageIndex = rememberSaveable { mutableStateOf(0) }

    LaunchedEffect(Unit) {
        if (images.size == 1) return@LaunchedEffect
        while (true) {
            delay(interval.toLong())
            imageIndex.value = (imageIndex.value + 1) % images.size
        }
    }
a
With almost any navigation library, when another screen is pushed to the stack, the previous screen's Composable exits the composition, and then re-enters again. The value should be saved (e.g. using rememberSaveable), or you can move this logic to the component/ViewModel. The latter option looks preferable to me.
v
@Arkadii Ivanov understood, this is how
remember
works I dont use Component for this ui element as its a card used in a Lazy List, Would using
rememberSaveable
cause any performance issues?
a
I mean, there still should be a component that's being moved to the back stack, right? I would place that counter logic there instead, and keep the view stateless. Using rememberSaveable is also fine, shouldn't cause any performance issues.
v
I am making this a reusable component, so I cant keep the logic inside the Screen level component I think i can make this a component, passing the childContext from the parent component
a
Yep, in this case I would recommend extracting a component for this widget. But it's not obligatory.
v
Yes, thanks for the help
👍 1