Android Room无法在主线程上访问数据库,因为它可能会长时间锁定UI

发布于 2025-02-02 05:39:26 字数 1685 浏览 4 评论 0原文

我正在使用Hilt和coroutine Worker请求API,并且在获取数据后,我想将其提升到我的房间存储库,这里的问题即使我使用withContext(dispatchers.io)

无法在主线程上访问数据库,因为它可能可能有可能 锁定UI长时间。

顺便说一句,我不想​​在房间上启用 lastermainthreadqueries(),仍然想在io线程

和工作代码中更新我的回购:

@HiltWorker
class CheckForNewProfilePhotos @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    private val usersAPI: UsersAPI,
    private val rUserRepository: RUserRepository
) :
    CoroutineWorker(appContext, workerParams) {
    override suspend fun doWork(): Result {
        withContext(Dispatchers.IO) {

            val usersIdsToFetch = inputData.getLongArray("usersIdsToFetch")

            val response = usersIdsToFetch?.let {
                usersAPI.getMultipleUsers(
                    GetMultipleUsers(it.toList())
                )
            }

            response?.enqueue(object : Callback<List<User>> {
                override fun onResponse(
                    call: Call<List<User>>,
                    response: Response<List<User>>
                ) {

                    response.body()?.let {
                        rUserRepository.upsert(it.toMutableList())
                        //                      conversationRepository.updateUserData(it)
                    }
                }

                override fun onFailure(call: Call<List<User>>, t: Throwable) {
                    Result.retry()
                }
            })

            return@withContext Result.success()
        }

        return Result.success()
    }
}

i am using Hilt and Coroutine Worker to request API and after fetching data i wanna upsert it to my room repositry , the problem here is even i used withContext(Dispatchers.IO) it trow this error:

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

by the way i don't wanna enable allowMainThreadQueries() on my room and still wanna update my repo in IO Thread

and my worker code:

@HiltWorker
class CheckForNewProfilePhotos @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    private val usersAPI: UsersAPI,
    private val rUserRepository: RUserRepository
) :
    CoroutineWorker(appContext, workerParams) {
    override suspend fun doWork(): Result {
        withContext(Dispatchers.IO) {

            val usersIdsToFetch = inputData.getLongArray("usersIdsToFetch")

            val response = usersIdsToFetch?.let {
                usersAPI.getMultipleUsers(
                    GetMultipleUsers(it.toList())
                )
            }

            response?.enqueue(object : Callback<List<User>> {
                override fun onResponse(
                    call: Call<List<User>>,
                    response: Response<List<User>>
                ) {

                    response.body()?.let {
                        rUserRepository.upsert(it.toMutableList())
                        //                      conversationRepository.updateUserData(it)
                    }
                }

                override fun onFailure(call: Call<List<User>>, t: Throwable) {
                    Result.retry()
                }
            })

            return@withContext Result.success()
        }

        return Result.success()
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

も让我眼熟你 2025-02-09 05:39:26

您可以使用使用使用使用使用使用suppendCoroutinesuppendCancellableCoroutine Builder functions suppend supperd supper supperd supper Bualder函数然后调用并将结果主体插入数据插入DB之后:

private suspend fun makeRequest() = suspendCoroutine { continuation ->
    val usersIdsToFetch = inputData.getLongArray("usersIdsToFetch")

    val response = usersIdsToFetch?.let {
        usersAPI.getMultipleUsers(GetMultipleUsers(it.toList()))
    } 

    response?.enqueue(object : Callback<List<User>> {
            override fun onResponse(
                call: Call<List<User>>,
                response: Response<List<User>>
            ) {
                continuation.resume(response.body()) // resumes suspended coroutine
            }

            override fun onFailure(call: Call<List<User>>, t: Throwable) {
                Result.retry()
                continuation.resume(null) // or continuation.resumeWithException(t) if you want to handle Exceptions
            }
    })
}

override suspend fun doWork(): Result {
    return withContext(Dispatchers.IO) {
        val body = makeRequest()
        return@withContext if (body != null) {
            rUserRepository.upsert(it.toMutableList())
            // conversationRepository.updateUserData(it)
            Result.success()
        } else {
            Result.retry()
        }
    }
}

You can convert the Callback<List<User>> to a suspend function using suspendCoroutine or suspendCancellableCoroutine builder functions and then after calling it and getting a result body insert data to the DB:

private suspend fun makeRequest() = suspendCoroutine { continuation ->
    val usersIdsToFetch = inputData.getLongArray("usersIdsToFetch")

    val response = usersIdsToFetch?.let {
        usersAPI.getMultipleUsers(GetMultipleUsers(it.toList()))
    } 

    response?.enqueue(object : Callback<List<User>> {
            override fun onResponse(
                call: Call<List<User>>,
                response: Response<List<User>>
            ) {
                continuation.resume(response.body()) // resumes suspended coroutine
            }

            override fun onFailure(call: Call<List<User>>, t: Throwable) {
                Result.retry()
                continuation.resume(null) // or continuation.resumeWithException(t) if you want to handle Exceptions
            }
    })
}

override suspend fun doWork(): Result {
    return withContext(Dispatchers.IO) {
        val body = makeRequest()
        return@withContext if (body != null) {
            rUserRepository.upsert(it.toMutableList())
            // conversationRepository.updateUserData(it)
            Result.success()
        } else {
            Result.retry()
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文