Is the Kotlin Structured Concurrency [coroutine] model scoped to UI suitable for DB writes?

Viewed 246

I'm specifically concerned about inserting user initiated data into the local database.

The following pattern is prevalent in examples (including from official sources, e.g. JetBrains, Google/Android) for using Kotlin coroutines in conjunction with [Android Architecture Components] ViewModels.

class CoroutineScopedViewModel : ViewModel(), CoroutineScope {
    private val _job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + _job

    override fun onCleared() {
        super.onCleared()
        _job.cancel()
    }

    fun thisIsCalledFromTheUI() = launch {
        /* do some UI stuff on the main thread */
        withContext(Dispatchers.IO) {
            try {
                /* do some IO, e.g. inserting into DB */
            } catch (error: IOException) {
                /* do some exception handling */
            }
        }
    }
}

It's my understanding of the documentation that in the above example the coroutines started in the UI context (defined through coroutineContext) will be cancelled when the ViewModel is destroyed, but that the code in the withContext(Dispatchers.IO) block will get to run to completion.

But, before I go about refactoring my project from the (pre-1.0.0) globally scoped (launch/async) coroutine model, I feel I need to just have some things clarified:

Is my reading of the documentation correct? Or, will destruction of the viewmodel before the withContext(Dispatchers.IO) block runs to completion trigger cancellation of that job too? I.e. can this model be used for inserting data into my DB, or could some strange timing issue arise where the user hits back or otherwise causes the ViewModel owner to close that ends up losing the data?

I don't want to inadvertently introduce a timing bug because I misunderstood something and therefor converted my code to a model similar to the one shown above.

EDIT:

So, I decided to do a little test, and it seems to me that all those examples using this model to write to the database may have a fundamental bug.

Modifying the code to log what happens, as such:

class ChildViewModel : ViewModel(), CoroutineScope {
    private val _job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + _job

    override fun onCleared() {
        super.onCleared()
        Log.d("onCleared", "Start")
        _job.cancel()
        Log.d("onCleared", "End")
    }

    fun thisIsCalledFromTheUI() = launch {
        Log.d("thisIsCalledFromTheUI", "Start")
        GlobalScope.launch(Dispatchers.IO) {
            Log.d("GlobalScope", "Start")
            delay(15000)
            Log.d("GlobalScope", "End")
        }
        withContext(Dispatchers.IO) {
            Log.d("withContext", "Start")
            delay(10000)
            Log.d("withContext", "End")
        }
        Log.d("thisIsCalledFromTheUI", "End")
    }
}

Results in this, if you let it run to completion:

D/thisIsCalledFromTheUI: Start
D/GlobalScope: Start
D/withContext: Start
D/withContext: End
D/thisIsCalledFromTheUI: End
D/GlobalScope: End

But, if you close the Fragment/Activity (not the app) before withContext ends, you get this:

D/thisIsCalledFromTheUI: Start
D/GlobalScope: Start
D/withContext: Start
D/GlobalScope: End

Which indicates, to me at least, that you cannot use this to write non-transient data to the DB.

1 Answers

It's my understanding of the documentation that in the above example the coroutines started in the UI context (defined through coroutineContext) will be cancelled when the ViewModel is destroyed, but that the code in the withContext(Dispatchers.IO) block will get to run to completion.

This isn't a correct reading of the documentation. withContext doesn't start another coroutine, it just changes the current coroutine's context for the duration of its block. Therefore this coroutine will get cancelled, as well as all other coroutines you start without providing a new parent context that has a different job associated with it (or no job at all, like the GlobalScope).

However, your proposed idea to use the GlobalScope for persistent operations is just a local patch for the scenario you're testing, you're still not getting a guarantee it will run to completion. The user can exit the application completely and Android can kill the process.

Therefore, if your goal is building a truly robust application, you must accommodate the fact that, until the coroutine completes, no information was written to the DB. Hopefully you run the operation within a DB transaction that will automatically roll back if your program gets killed, otherwise it will be impossible to prevent inconsistencies.

Related