Guest User

Untitled

a guest
Sep 14th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  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
Add Comment
Please, Sign In to add comment