google-developer-training/basic-android-kotlin-compose-training-inventory-app

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

Opened this issue · 0 comments

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.