The question about UI layer and unidirectional data flow (UDF). Let's we have DetailFragment
with EditText
:
When user open existing detail, text filled from
StateFlow<DetailUiState>
byViewModel
.Now user changing text,
DetailFragment
send new text toViewModel
that update UI state and due tocollect
fragment receive updated state. So fragment callsetText
that triggers to send same text toViewModel
again.If we haven't update UI State when receive new text, for any configuration changes (screen rotation) fragment receive old text value when re-create.
How to exit from such loop?
data class DetailUiState(
val text: String
)
class DetailViewModel {
private val _uiState = MutableStateFlow(DetailUiState("first text"))
val uiState = _uiState.asStateFlow()
fun onTextChanged(newValue: String) {
_uiState.value = DetailUiState(newValue)
}
}
class DetailFragment {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
repeatOnStartedLatest(viewModel.uiState) { // flow.collect shortcut
binding.editText.setText(it.text)
}
binding.editText.doAfterTextChanged {
viewModel.onTextChanged(binding.editText.getTextAsString())
}
}
}