S.
11/27/2023, 7:42 PMS.
11/27/2023, 7:46 PM.dispatchers(
inputsDispatcher = Dispatchers.Main.immediate,
sideJobsDispatcher = Dispatchers.Default,
interceptorDispatcher = Dispatchers.Default,
)
as well as using intermediary mutableStateOf
, which also results in the above gif
@Composable
fun CustomTextField(
value: String,
onValueChange: (String) -> Unit,
) {
var text by remember { mutableStateOf(value) }
LaunchedEffect(value) {
text = value
}
OutlinedTextField(
value = text,
onValueChange = onValueChange,
)
}
S.
11/27/2023, 8:05 PMonValueChange = {
text = it
onValueChange(it)
}
S.
11/27/2023, 8:05 PMCasey Brooks
11/28/2023, 5:26 PMremember { mutableStateOf() }
block, and why the Compose team is working on a new implementation of TextFields to help mitigate the issues. This article is a good intro to the new TextField APIs, though do note that it’s still a WIP and not fully integrated into the Material libraries yet. Also, I haven’t actually tried out the new TextField to know exactly how well it works with the MVI model.
The solution I typically use in the current TextField is to essentially just keep a copy of the TextFieldState’s text in the VM state, rather than having the VM state directly control the TextField. Something like this should work:
var textFieldState by remember { mutableStateOf(TextFieldValue()) }
LaunchedEffect(uiState.text) {
// after a very short delay, update the textFieldState with the text in the VM state.
// this allows the VM to directly set the TextField's text, but avoid issues with UI inconsistency.
// Ideally, this would only really apply if the VM manually changed the text (loaded it from DB, for example),
// and not as a result of normal user-entered input
delay(25.milliseconds)
if (uiState.text != textFieldState.text) {
textFieldState = textFieldState.copy(text = uiState.text)
}
}
TextField(
value = textFieldState,
onValueChange = {
// set and display the text in the composition to maintain consistency
textFieldState = it
// send a copy of the text to the VM for validation, etc.
postInput(ExampleContract.Inputs.TextChanged(it.text))
},
)
S.
11/28/2023, 5:53 PM