-
-
Save shakil807g/01490c48638846240fc12707dfb9013f to your computer and use it in GitHub Desktop.
A job that automatically gets cancelled when the lifecycle is destroyed. Meant to be used as a parent to your coroutines in lifecycle aware components.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.arch.lifecycle.GenericLifecycleObserver | |
import android.arch.lifecycle.Lifecycle | |
import android.arch.lifecycle.Lifecycle.Event.ON_DESTROY | |
import android.arch.lifecycle.LifecycleOwner | |
import kotlinx.coroutines.experimental.CoroutineScope | |
import kotlinx.coroutines.experimental.Dispatchers | |
import kotlinx.coroutines.experimental.Job | |
import kotlinx.coroutines.experimental.android.Main | |
fun Lifecycle.createJob(cancelEvent: Lifecycle.Event = ON_DESTROY): Job = Job().also { job -> | |
addObserver(object : GenericLifecycleObserver { | |
override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) { | |
if (event == cancelEvent) { | |
removeObserver(this) | |
job.cancel() | |
} | |
} | |
}) | |
} | |
private val lifecycleJobs = mutableMapOf<Lifecycle, Job>() | |
val Lifecycle.job: Job | |
get() = lifecycleJobs[this] ?: createJob().also { | |
lifecycleJobs[this] = it | |
it.invokeOnCompletion { _ -> lifecycleJobs -= this } | |
} | |
private val lifecycleCoroutineScopes = mutableMapOf<Lifecycle, CoroutineScope>() | |
val Lifecycle.coroutineScope: CoroutineScope | |
get() = lifecycleCoroutineScopes[this] ?: createJob().let { | |
val newScope = CoroutineScope(it + Dispatchers.Main) | |
lifecycleCoroutineScopes[this] = newScope | |
it.invokeOnCompletion { _ -> lifecycleCoroutineScopes -= this } | |
newScope | |
} | |
val LifecycleOwner.coroutineScope get() = lifecycle.coroutineScope |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment