Шаги:
- введите текст в TextField
- нажмите «Сбросить текст»
Модель просмотра
Код: Выделить всё
@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()) }
}
}
Код: Выделить всё
data class SomeState(
val text: String? = null,
)
Код: Выделить всё
@Composable
fun SomeView(modifier: Modifier = Modifier) {
val viewModel = hiltViewModel()
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")
}
}
}
Код: Выделить всё
fun resetText() {
viewModelScope.launch {
state.update { it.copy(text = "") }
delay(100)
state.update { it.copy(text = null) }
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... model-flow
Мобильная версия