Search code examples
androidkotlinandroid-roomandroidxkotlin-coroutines

Coroutine keeps crashing without showing error


I'm developing in MVP. In my Presenter, I call my Repository thanks to the suspend function. In this suspend function, I launch a Coroutine - not on the main thread. When this coroutine is finished, I want to execute some code: I am using withContext() in order to do so.

In my Repository, I am launching a Coroutine (and maybe I am wrong) to insert my data, using DAO, in my Room database.

When I debug my application, it goes into my Presenter but crashes before going into my Repository.

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}")
            }
        }
    }

Repository

    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}")
            }
        }

    }

I have no error shown in my logcat.

EDIT:

Scope initialization

    private var parentJob: Job = Job()

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

    private val scope = CoroutineScope(coroutineContext)

val uiContext: CoroutineContext = Dispatchers.Main (initialized in my class constructor)

Stack trace

enter image description here


Solution

  • I finally found the answer!

    Thanks to @sergiy I read part II of this article https://medium.com/androiddevelopers/coroutines-on-android-part-ii-getting-started-3bff117176dd and it mentions that you can't catch error except Throwable and CancellationException.

    So instead of catching Exception, I traded it for Throwable. And finally I had an error shown in my logcat.

    I am using Koin to inject my repository and all. I was missing my androidContext() in my Koin application. That's it.