Persist data with Room: wrong implementation of database access in the codelab.
Opened this issue · 0 comments
angelomarzocchi commented
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.