With kotlin flow you can use debounce, which is designed specifically for such cases. That way, as long as the user enters text, saveToDatabase will not be called, and when he does not enter a character for some time (in my example it is one second) - the flow will be emitted.
Also during Compose Navigation the view model may be destroyed (and the coroutine will be cancelled) if the screen is closed, in that case I also save the data inside onCleared to make sure that nothing is missing.
class ScreenViewModel: ViewModel() {
private val _text = MutableStateFlow("")
val text: StateFlow<String> = _text
init {
viewModelScope.launch {
@OptIn(FlowPreview::class)
_text.debounce(1000)
.collect(::saveToDatabase)
}
}
fun updateText(text: String) {
_text.value = text
}
override fun onCleared() {
super.onCleared()
saveToDatabase(_text.value)
}
private fun saveToDatabase(text: String) {
}
}
@Composable
fun ScreenView(
viewModel: ScreenViewModel = viewModel()
) {
val text by viewModel.text.collectAsState()
TextField(value = text, onValueChange = viewModel::updateText)
}
@OptIn(FlowPreview::class) means that the API may be changed in the future. If you don't want to use it now, see the replacement here.