Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

346
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda