Guest User

JobManager

a guest
Jul 5th, 2022
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.41 KB | None | 0 0
  1. package jobmanager
  2.  
  3. import kotlin.coroutines.*
  4. import kotlinx.coroutines.*
  5.  
  6. import ktx.async.*
  7.  
  8. typealias TaskMap = MutableMap<String, Job>
  9.  
  10. val launchMap: TaskMap = mutableMapOf()
  11.  
  12. fun NamedLazyJob(name: String = "Default", dispatcher: CoroutineContext = Dispatchers.KTX, task: suspend CoroutineScope.()->Unit): Job = launchMap.getOrPut(name,
  13.     {KtxAsync.launch(dispatcher, CoroutineStart.LAZY) {
  14.         KtxAsync.task()
  15.     }})
  16.    
  17. fun Job.startIf(predicate: ()->Boolean) = apply {
  18.     if(!isActive && predicate()) start()
  19. }
  20. fun Job.remove(name: String = "Default") = apply {
  21.     if(isCompleted) launchMap.remove(name)
  22. }
  23.  
  24. val asyncMap: MutableMap<String, Deferred<Any>> = mutableMapOf<String, Deferred<Any>>()
  25.  
  26. fun NamedAsync(name: String = "Default", dispatcher: CoroutineContext = Dispatchers.KTX, task: suspend CoroutineScope.()-> Any) = asyncMap.getOrPut(name,
  27.     {KtxAsync.async(dispatcher, CoroutineStart.LAZY) {
  28.         KtxAsync.task()
  29. }})
  30.  
  31. fun Deferred<Any>.startIf(predicate: ()->Boolean) = apply {
  32.     if(!isActive && predicate()) start()
  33. }
  34.  
  35. fun Deferred<Any>.resultIfElse(predicate: ()->Boolean, action: ()-> Any? = {null}): Any?  {
  36.     val def = this
  37.     var result: Any? = null
  38.     KtxAsync.launch(Dispatchers.Unconfined) {
  39.         result = if(def.isCompleted && predicate()) def.await() else action()
  40.     }
  41.     return result
  42. }
  43.  
  44. fun Deferred<Any>.remove(name: String = "Default") = apply {
  45.     if(isCompleted) asyncMap.remove(name)
  46. }
Advertisement
Add Comment
Please, Sign In to add comment