Skip to content

Instantly share code, notes, and snippets.

@parthdesai1208
Last active January 10, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parthdesai1208/a28d441047b9bb8090b7ca6f77e25691 to your computer and use it in GitHub Desktop.
Save parthdesai1208/a28d441047b9bb8090b7ca6f77e25691 to your computer and use it in GitHub Desktop.
restore state in compose
************************************************************************************************************************************
restore state of list of Int, String using rememberSaveable
************************************************************************************************************************************
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.toMutableStateList
@Composable
fun <T : Any> rememberMutableStateListOf(vararg elements: T): SnapshotStateList<T> {
return rememberSaveable(
saver = listSaver(
save = { stateList ->
if (stateList.isNotEmpty()) {
val first = stateList.first()
if (!canBeSaved(first)) {
throw IllegalStateException("${first::class} cannot be saved. By default only types which can be stored in the Bundle class can be saved.")
}
}
stateList.toList()
},
restore = { it.toMutableStateList() }
)
) {
elements.toList().toMutableStateList()
}
}
use it like,
val list = rememberMutableStateListOf<Int>()
************************************************************************************************************************************
************************************************************************************************************************************
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment