Cancel launched Coroutines onDestroy
from the docs of CoroutineScope
- Manual implementation of this interface is not recommended, implementation by delegation should be preferred instead.
- By convention, the [context of a scope][CoroutineScope.coroutineContext] should contain an instance of a [job][Job] to enforce structured concurrency.
We can convert
class BrowserActivity : DuckDuckGoActivity(), CoroutineScope
to
class BrowserActivity : DuckDuckGoActivity(), CoroutineScope by MainScope()
get rid of
override val coroutineContext: CoroutineContext get() = SupervisorJob() + Dispatchers.Main
because, from the docs of MainScope :
public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
and finally, getting to the issue (I think), we should cancel all coroutines started in this scope when the activity is destroyed
override fun onDestroy() { cancel() super.onDestroy() }
I can take care of this and other activities where this might be happening.
Thanks for the suggestion. I agree with you and we already included MainScope in one of our latest features inside our project. But still, we need to experiment a little bit more with this and validate that covers all our scenarios.
Thanks for the suggestion. I agree with you and we already included
MainScopein one of our latest features inside our project. But still, we need to experiment a little bit more with this and validate that covers all our scenarios.
Cool, what are your thoughts regarding cancelling all coroutines onDestroy or onStop?
We do agree on canceling on those lifecycle methods, and using MainScope will take care of that for us. But we still need to go deeper and understand if we can combine MainScope with custom ExceptionHandler. Happy to see you so proactive on this issue. Thanks for that!
Another option is to use the lifecycleScope that AndroidX already offers to you in any LifecycleOwner (including ComponentActivity, Fragment, and NavBackStackEntry), those are automatically wired to your lifecycle and will be cancelled when the lifecycle reaches destroy state.
For more details, see here.
Closing this stall issue. This doesn’t apply anymore.