gpt4 book ai didi

kotlin - 改造成功后,协程问题将数据插入房间数据库

转载 作者:行者123 更新时间:2023-12-02 13:29:18 24 4
gpt4 key购买 nike

我正在使用Retrofit从API服务器获取新闻记录,如果成功,则它将使用insertAll作为以下代码将数据写入 session 室数据库,但是此代码会产生如下错误
无法访问主线程上的数据库,因为它可能长时间锁定用户界面

我尝试将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}")
}
}


})

}
}

最佳答案

您的代码应看起来像这样。用suspendCoroutine隔离回调代码,以便withContext(Dispatchers.IO)之类的东西可以按预期工作。

suspend fun refreshNews(queryString: String="", page: Int = 1) {
val call = RetrofitClient.instance.getAllNews(buatObjectNewsQuery(queryString), page)
val response = suspendCoroutine { cont ->
call.enqueue(object : Callback<NewsGetAllResponse> {
override fun onFailure(call: Call<NewsGetAllResponse>, t: Throwable) {
cont.resumeWithException(t)
}

override fun onResponse(
call: Call<NewsGetAllResponse>,
response: Response<NewsGetAllResponse>
) {
const.resume(response)
}
})
}

val newslist = response.body()?.asDatabaseModel()
if (newslist != null) {
withContext(Dispatchers.IO) {
database.databaseNewsDao.insertAll(*newslist)
Timber.tag(TAG).i("dalam refresh jumlah data ${newslist.size}")
}
}
}

编辑:

理想情况下,您想为此创建扩展功能,因此阅读起来看起来并不那么吓人。
suspend fun <T> Call<T>.awaitResponse(): Response<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
continuation.resume(response)
}

override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}

suspend fun refreshNews(queryString: String="", page: Int = 1) {
val call = RetrofitClient.instance.getAllNews(buatObjectNewsQuery(queryString), page)
val response = call.awaitResponse()

val newslist = response.body()?.asDatabaseModel()
if (newslist != null) {
withContext(Dispatchers.IO) {
database.databaseNewsDao.insertAll(*newslist)
Timber.tag(TAG).i("dalam refresh jumlah data ${newslist.size}")
}
}
}

关于kotlin - 改造成功后,协程问题将数据插入房间数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62391775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com