andfun-kotlin-sleep-tracker
andfun-kotlin-sleep-tracker copied to clipboard
Issue with tonight.value (Cannot invoke setValue on a background thread)
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())
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()) } }
To fix this, I changed the SleepDatabaseDao interface:
replace fun getTonight(): SleepNight?
with fun getTonight(): LiveData<SleepNight?>
and update the SleepTrackerViewModel accordingly