Android icon indicating copy to clipboard operation
Android copied to clipboard

Cancel launched Coroutines onDestroy

Open ParanoidBeing opened this issue 5 years ago • 4 comments

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.

ParanoidBeing avatar Feb 07 '20 12:02 ParanoidBeing

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.

cmonfortep avatar Feb 12 '20 14:02 cmonfortep

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.

Cool, what are your thoughts regarding cancelling all coroutines onDestroy or onStop?

ParanoidBeing avatar Feb 13 '20 05:02 ParanoidBeing

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!

cmonfortep avatar Feb 15 '20 17:02 cmonfortep

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.

marcellogalhardo avatar Aug 15 '21 16:08 marcellogalhardo

Closing this stall issue. This doesn’t apply anymore.

malmstein avatar Jun 23 '23 09:06 malmstein