andfun-kotlin-sleep-tracker icon indicating copy to clipboard operation
andfun-kotlin-sleep-tracker copied to clipboard

Issue with tonight.value (Cannot invoke setValue on a background thread)

Open alex-1987 opened this issue 2 years ago • 2 comments

Hi i found an error in the SleepTrackerViewModel.kt

If i use the code: private fun initializeTonight() { uiScope.launch { tonight.value = getTonightFromDatabase() } } i get an Error:

java.lang.IllegalStateException: Cannot invoke setValue on a background thread

To fix the Problem replace all tonight.value = getTonightFromDatabase() with tonight.postValue(getTonightFromDatabase())

alex-1987 avatar Sep 06 '22 08:09 alex-1987

Unfortunately, the proposed solution didn't work for me... when I run the app, I get this error:

Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

caused by

private fun initializeTonight() { viewModelScope.launch { tonight.postValue(getTonightFromDatabase()) } }

devrodmastria avatar Oct 12 '22 02:10 devrodmastria

To fix this, I changed the SleepDatabaseDao interface:

replace fun getTonight(): SleepNight? with fun getTonight(): LiveData<SleepNight?>

and update the SleepTrackerViewModel accordingly

devrodmastria avatar Oct 12 '22 03:10 devrodmastria