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

Mikołaj Kąkol

01/15/2021, 7:49 PM
hello fellow composers, question about state keeping. I have two tabs. Only one of them is visible at given time, hence when
tabA
is visible
tabB
is not in composition tree. My problem is that when I switch between them state is not remembered, for example scroll state. How can I tell to compose to remember this discarded tab, that it can be needed soon? (sample code in thread)
Copy code
@Composable
fun Testing() = Column {

    val tabIndex = remember { mutableStateOf(0) }

    Row {
        Button(onClick = {
            tabIndex.value = tabIndex.value - 1
        }) { Text("Previous tab") }
        Button(onClick = {
            tabIndex.value = tabIndex.value + 1
        }) { Text("Next tab") }
    }

    if (tabIndex.value % 2 == 0) {
        ContentForTab1(1)
    } else {
        ContentForTab2(2)
    }
}

@Composable
fun ContentForTab1(tabIndex: Int) {
    ScrollableColumn {
        (0..100).map { Text("Item in tab: $tabIndex number $it") }
    }
}

@Composable
fun ContentForTab2(tabIndex: Int) {
    ScrollableColumn {
        (0..100).map { Text("Item in tab: $tabIndex number $it") }
    }
}
a

Alex Petitjean

01/15/2021, 7:53 PM
If you use
LazyColumn
, I think you could lift the
LazyListState
out of the tabs and pass it into them (idk if there's a state object for
ScrollableColumn
, but that method is deprecated anyway, so you might want to just switch)
m

Mikołaj Kąkol

01/15/2021, 7:55 PM
that would basically require to move all my state to caller, which I wanted to avoid. So my tab container wouldn’t care about what is inside each tab
especially if those things are not crucial for typical business logic, all I want is them to remember where was scroll, but maybe it’s old thinking now 😄
t

Tash

01/15/2021, 9:28 PM
Sounds like the state does need to be extracted up the hierarchy to a common component. This concept of “state-hoisting” is explained in these docs.
m

Mikołaj Kąkol

01/30/2021, 8:27 PM
good answer is to use RestorableStateHolder, hope you will gain from that knowledge 🙂