Make sure coroutine completes without cancelation

Viewed 194

I'm writing an app that communicates through JNI with a data controller. When the main activity dies (single activity app) I wanted to clear the memory. To do that I'm using coroutines and activity's lifecycle scope with context of Dispatchers.IO. Is it possible (at least in theory) that activity's scope is cancelled before execution of withContext { ... completes? As far as I understand coroutine it is, since withContext is a suspend function and handles cancelation. And if this is correct, what would be preferred way of launching some cleanup code that should be executed regardless?

override fun onDestroy() {
    lifecycleScope.launch {
        withContext(Dispatchers.IO) {
            dataStore.disconnectController()
        }
    }
    super.onDestroy()
}
0 Answers
Related