Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Add Comment
Please, Sign In to add comment