Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

350
Visualizações
Jetpack Compose and Room DB: Performance overhead of auto-saving user input?

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda