Can someone tell me why otp
value not updated by resetText
?
Steps:
- type some text in TextField
- click “Reset text”
Is it bug or some issues with my code?
ViewModel
@HiltViewModel
class MyViewModel @Inject constructor() : ViewModel() {
val state = MutableStateFlow(SomeState())
fun resetText() {
state.update { it.copy(text = null) }
}
fun changeText() {
state.update { it.copy(text = Math.random().toString()) }
}
}
State class
data class SomeState(
val text: String? = null
)
View
@Composable
fun SomeView(modifier: Modifier = Modifier) {
val viewModel = hiltViewModel<MyViewModel>()
val state by viewModel.state.collectAsState()
var otp by rememberSaveable(state.text) { mutableStateOf(state.text) }
Column(
modifier = modifier
.padding(horizontal = 16.dp)
.background(Color.White)
.fillMaxSize(),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
TextField(
value = otp.orEmpty(),
onValueChange = { otp = it }
)
Button(onClick = { viewModel.resetText() }) {
Text(text = "reset text")
}
Button(onClick = { viewModel.changeText() }) {
Text(text = "Change text")
}
}
}
P.S. I made it work by changing resetText to
fun resetText() {
viewModelScope.launch {
state.update { it.copy(text = "") }
delay(100)
state.update { it.copy(text = null) }
}
}
but it’s obviously bad option