Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!