Skip to content

Instantly share code, notes, and snippets.

@suclike
Forked from LouisCAD/LifecycleCoroutines.kt
Created August 15, 2018 21:47
Show Gist options
  • Save suclike/8ab129544d2898e764ade9ca6e0fc739 to your computer and use it in GitHub Desktop.
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.
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 }
}
@LouisCAD
Copy link

LouisCAD commented Sep 7, 2018

@suclike invokeOnCancellation should be replaced by invokeOnCompletion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment