Home > front end >  Jetpack Compose and Room DB: Performance overhead of auto-saving user input?
Jetpack Compose and Room DB: Performance overhead of auto-saving user input?

Time:10-25

I'm writing an app with Jetpack Compose that lets the user input text in some TextFields and check a few radio buttons.

This data is then stored in a Room database.

Currently, I have a "save" button at the bottom of the screen, with a "Leave without saving?" popup.

However, I'd like to get rid of the save button entirely and have it autosave data as it's being typed.

Would the repeated DB queries from typing cause any performance issues? And are there any established best practices for this sort of thing?

CodePudding user response:

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.

  • Related