Last active
January 10, 2023 16:52
-
-
Save parthdesai1208/a28d441047b9bb8090b7ca6f77e25691 to your computer and use it in GitHub Desktop.
restore state in compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
************************************************************************************************************************************ | |
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