Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist data with Room: wrong implementation of database access in the codelab. #165

Open
angelomarzocchi opened this issue Dec 18, 2024 · 0 comments

Comments

@angelomarzocchi
Copy link

URL of codelab: https://developer.android.com/codelabs/basic-android-kotlin-compose-persisting-data-room?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-6-pathway-2%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-persisting-data-room#8

In which task and step of the codelab can this issue be found? Task 9: Add the save functionality

Describe the problem
implementing the onSaveClick like described leads to a crash of the app . I get a " java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time."

I had to implement the saveItem functionality in the ViewModel like this to make it work :
fun saveItem() {
viewModelScope.launch(Dispatchers.IO) {
if (validateInput())
itemsRepository.insertItem(itemUiState.itemDetails.toItem())
}
}

This also seems to be the cleaner solution! I don't see the point of having to deal with coroutines in the UI, it does not follow the Single Responsability principle in my opinion.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant