daily pastebin goal
79%
SHARE
TWEET

Untitled

a guest Sep 14th, 2018 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import android.arch.lifecycle.GenericLifecycleObserver
  2. import android.arch.lifecycle.Lifecycle
  3. import android.arch.lifecycle.Lifecycle.Event.ON_DESTROY
  4. import android.arch.lifecycle.LifecycleOwner
  5. import kotlinx.coroutines.experimental.CoroutineScope
  6. import kotlinx.coroutines.experimental.Dispatchers
  7. import kotlinx.coroutines.experimental.Job
  8. import kotlinx.coroutines.experimental.android.Main
  9.  
  10. fun Lifecycle.createJob(cancelEvent: Lifecycle.Event = ON_DESTROY): Job = Job().also { job ->
  11.     addObserver(object : GenericLifecycleObserver {
  12.         override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) {
  13.             if (event == cancelEvent) {
  14.                 removeObserver(this)
  15.                 job.cancel()
  16.             }
  17.         }
  18.     })
  19. }
  20.  
  21. private val lifecycleJobs = mutableMapOf<Lifecycle, Job>()
  22.  
  23. val Lifecycle.job: Job
  24.     get() = lifecycleJobs[this] ?: createJob().also {
  25.         lifecycleJobs[this] = it
  26.         it.invokeOnCompletion { _ -> lifecycleJobs -= this }
  27.     }
  28. private val lifecycleCoroutineScopes = mutableMapOf<Lifecycle, CoroutineScope>()
  29.  
  30. val Lifecycle.coroutineScope: CoroutineScope
  31.     get() = lifecycleCoroutineScopes[this] ?: createJob().let {
  32.         val newScope = CoroutineScope(it + Dispatchers.Main)
  33.         lifecycleCoroutineScopes[this] = newScope
  34.         it.invokeOnCompletion { _ -> lifecycleCoroutineScopes -= this }
  35.         newScope
  36.     }
  37.  
  38. val LifecycleOwner.coroutineScope get() = lifecycle.coroutineScope
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top