물론 Flow나 LiveData를 사용하면 다 해결됩니다만 공부를 위해서 MutableList를 사용해보고 있습니다.
'Cannot access database on the main thread since it may potentially lock the UI for a long period of time.' 이런 오류 메시지 때문에 viewModelScope를 사용했고 Dispatchers.IO로 RoomDB에서 items를 가지고 오는데 성공했습니다.
class CheckListViewModel(
val app: Application
): AndroidViewModel(app) {
var items: MutableList<Item> = mutableListOf()
// fun getAllCategory(category: String) {
// items = RoomDB.getInstance(app)?.itemDao()!!.getAllCategory(category)
// Log.i(TAG, "items: ${items.toString()}")
// }
fun getAllCategory(category: String) = viewModelScope.launch(Dispatchers.IO) {
items = RoomDB.getInstance(app)?.itemDao()!!.getAllCategory(category)
Log.i(TAG, "items: ${items.toString()}")
}
activity에서 items에 접근하는 게 문제인데요. 이게 어떨 때는 items를 받아 오고 어떨 때는 null을 반환합니다. 뭐 어떤 규칙이 있는 것도 아니고 오류 메시지를 보이는 것도 아니니 미치고 환장할 노릇입니다. 제 짧은 소견으로는 ViewModel에서 items를 받아오는 IO thread가 끝나는 여부에 따라 activity에 items를 정상적으로 보여주거나 그렇지 못하는 경우가 있는 게 아닌가 싶습니다. 제 생각이 맞는지요?
만일 그렇다면 ViewModel에서 items를 다 받아온 다음, 안전하게 activity에서 items에 접근하여 adapter로 뿌려줄 수 있는 방법이 있을까요?