【发布时间】:2020-10-05 01:47:40
【问题描述】:
我正在使用 Retrofit 从 API 服务器获取新闻记录,如果成功,它将使用 insertAll 将数据写入房间数据库,如下面的代码,但此代码会产生如下错误 无法访问主线程上的数据库,因为它可能会长时间锁定 UI
我尝试使用 Coroutine,withContext(Dispatchers.IO) 但我认为它不正确,谢谢您的帮助
suspend fun refreshNews(queryString: String="", page: Int = 1) {
withContext(Dispatchers.IO) {
RetrofitClient.instance.getAllNews(buatObjectNewsQuery(queryString), page)
.enqueue(object : Callback<NewsGetAllResponse> {
override fun onFailure(call: Call<NewsGetAllResponse>, t: Throwable) {
Timber.tag(TAG).i("sorry network error")
}
override fun onResponse(
call: Call<NewsGetAllResponse>,
response: Response<NewsGetAllResponse>
) {
val newslist = response.body()?.asDatabaseModel()
if (newslist != null) {
database.databaseNewsDao.insertAll(*newslist)
Timber.tag(TAG).i("dalam refresh jumlah data ${newslist.size}")
}
}
})
}
}
【问题讨论】:
-
我的回答不能解决你的问题吗?
-
@DominicFischer 我确实为您的答案标记了+1,但仍未测试您的答案,感谢您的详细解释
标签: kotlin coroutine kotlin-coroutines