android - 协程不断崩溃而不显示错误

标签 android kotlin android-room androidx kotlin-coroutines

我正在 MVP 方面进行开发。在我的 Presenter 中,我通过挂起功能调用我的存储库。在此挂起函数中,我启动了一个协程 - 不是在主线程上。 当这个协程完成时,我想执行一些代码:我正在使用 withContext() 来执行此操作。

在我的存储库中,我正在启动一个协程(也许我是错的)来使用 DAO 将我的数据插入到我的 Room 数据库中。

当我调试应用程序时,它会进入我的 Presenter,但在进入我的存储库之前崩溃。

主讲人

    override suspend fun insertUserResponse(activity: Activity, data: UserResponse) {
        scope.launch(Dispatchers.IO) {
            try {
                userResponseRepository.insertUserResponse(data)

                withContext(Dispatchers.Main) {
                    redirectToClientMainPage(activity)
                }
            } catch (error: Exception) {
                parentJob.cancel()
                Log.e("ERROR PRESENTER", "${error.message}")
            }
        }
    }

存储库

    override suspend fun insertUserResponse(userResponse: UserResponse) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val existingUser: UserResponse? =
                    userResponseDAO.searchUserByID(userResponse.profilePOJO.uniqueID)

                existingUser?.let {
                    userResponseDAO.updateUser(userResponse)
                } ?: userResponseDAO.insertUser(userResponse)
            } catch (error: Exception) {
                Log.e("ERROR REPOSITORY", "${error.message}")
            }
        }

    }

我的 logcat 中没有显示错误。

编辑:

范围初始化

    private var parentJob: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = uiContext + parentJob

    private val scope = CoroutineScope(coroutineContext)

val uiContext: CoroutineContext = Dispatchers.Main(在我的类构造函数中初始化)

堆栈跟踪

enter image description here

最佳答案

我终于找到答案了!

感谢@sergiy,我阅读了本文的第二部分https://medium.com/androiddevelopers/coroutines-on-android-part-ii-getting-started-3bff117176dd它提到除了 Throwable 和 CancellationException 之外,您无法捕获错误。

因此,我没有捕获 Exception,而是将其换成了 Throwable。最后我的 logcat 中显示了一个错误。

我正在使用 Koin 来注入(inject)我的存储库和所有内容。我的 Koin 应用程序中缺少 androidContext() 。 就是这样。

关于android - 协程不断崩溃而不显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64357669/

相关文章:

java - 从谷歌应用程序引擎发送post请求到php

android - 删除和添加 Activity 到后台堆栈

安卓/ Kotlin : Problems when sending data with URLConnection

android - 如何将 CameraView 与 Jetpack Compose 一起使用?

android - 搜索 View 与房间

android - 关系房间数据库 : The class must be either entity or database view

java - 到处覆盖 onStop?

android - 向本地主机发送发布请求

android - 哪个是组合多个 LiveData 的更好方法 : using MediatorLiveData or switchMap?

android - 如何使用 Android Room 运行多个 AND 查询?