Provides convenience extension methods to easily create a CoroutineScope
that is tied to the lifecycle of common Android classes (AppCompatActivity, AppCompatFragment, Dialog, View).
This allows you to auto-cancel any running coroutines that still have references to the Android framework object,
thus avoiding a memory leak of that reference.
Install via JCenter:
implementation 'be.rottenrei:android-coroutine-scopes:LATESTVERSION'You must use androidx.lifecycle and androidx.appcompat in order for these extensions to be able to listen to lifecycle events of activities and fragments.
class MyActivity : AppCompatActivity(), CoroutineScope {
override val coroutineContext by cancelOnDestroy()
}
class MyView : View(), CoroutineScope {
override val coroutineContext by cancelOnDetach()
}All coroutines started on this CoroutineScope are cancelled in the corresponding lifecycle event
(e.g. onDestroy or onDetachFromWindow).
LifecycleOwner.cancelOnDestroy()- cancelled when the activity/fragment is destroyedLifecycleOwner.cancelOnStop()- cancelled when the activity/fragment is stoppedLifecycleOwner.cancelOnPause()- cancelled when the activity/fragment is pausedDialog.cancelOnDismiss()- cancelled when the dialog is dismissedView.cancelOnDetach()- cancelled when the view is detached from its window
By default, all of these return a CoroutineContext with only a custom Job used to cancel
child coroutines. You can pass in a custom context that should be used instead (e.g. Dispatchers.Main) as well.