-
-
Save suclike/8ab129544d2898e764ade9ca6e0fc739 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.Job | |
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.invokeOnCancellation { lifecycleJobs -= this } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@suclike
invokeOnCancellation
should be replaced byinvokeOnCompletion