Carter
01/05/2024, 9:17 PMCarter
01/05/2024, 9:18 PMPablichjenkov
01/05/2024, 9:26 PMCarter
01/05/2024, 9:37 PMPablichjenkov
01/05/2024, 9:49 PMPablichjenkov
01/05/2024, 9:51 PMMofe Ejegi
01/05/2024, 10:28 PMMofe Ejegi
01/05/2024, 10:31 PMCarter
01/05/2024, 10:33 PMrememberSaveable
or using a ViewModel are the two ways to persist across Android configuration changes.Carter
01/05/2024, 10:33 PMCarter
01/05/2024, 10:35 PMfun main() {
val viewModel = ViewModel()
application {
Window(onCloseRequest = ::exitApplication, title = "KotlinProject") {
App(viewModelProvider = { viewModel })
}
}
}
class ViewModel {
val state = MutableStateFlow("")
}
@Composable
fun App(viewModelProvider: () -> ViewModel) {
val viewModel = viewModelProvider()
val textState = viewModel.state.collectAsState()
MaterialTheme {
MainContent(
textProvider = {textState.value},
updateText = { viewModel.state.value = it }
)
}
}
@Composable
fun MainContent(
textProvider: () -> String,
updateText: (String) -> Unit
) {
OutlinedTextField(
value = textProvider(),
onValueChange = updateText,
label = { Text("Enter text") },
modifier = Modifier.fillMaxWidth()
)
}
Mofe Ejegi
01/05/2024, 10:37 PMCarter
01/05/2024, 10:38 PMCarter
01/05/2024, 10:38 PMCarter
01/05/2024, 10:38 PMMitchell Syer
01/05/2024, 11:00 PMPablichjenkov
01/06/2024, 2:44 AMPablichjenkov
01/06/2024, 2:47 AMPablichjenkov
01/06/2024, 2:53 AMMofe Ejegi
01/06/2024, 11:44 AMMutableState
within the viewModel for managing the state, but the issue stems from managing the textField state across a reactive stream such as stateFlow, in which we can't always guarantee the order the data would be received.
I've really learned something new today.
PS: Ever notice how Compose Multiplatform already handles saving TextField data across configuration changes by default unlike Jetpack Compose? I wonder what the JB team did differently.Pablichjenkov
01/06/2024, 11:54 AM