Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jobmanager
- import kotlin.coroutines.*
- import kotlinx.coroutines.*
- import ktx.async.*
- typealias TaskMap = MutableMap<String, Job>
- val launchMap: TaskMap = mutableMapOf()
- fun NamedLazyJob(name: String = "Default", dispatcher: CoroutineContext = Dispatchers.KTX, task: suspend CoroutineScope.()->Unit): Job = launchMap.getOrPut(name,
- {KtxAsync.launch(dispatcher, CoroutineStart.LAZY) {
- KtxAsync.task()
- }})
- fun Job.startIf(predicate: ()->Boolean) = apply {
- if(!isActive && predicate()) start()
- }
- fun Job.remove(name: String = "Default") = apply {
- if(isCompleted) launchMap.remove(name)
- }
- val asyncMap: MutableMap<String, Deferred<Any>> = mutableMapOf<String, Deferred<Any>>()
- fun NamedAsync(name: String = "Default", dispatcher: CoroutineContext = Dispatchers.KTX, task: suspend CoroutineScope.()-> Any) = asyncMap.getOrPut(name,
- {KtxAsync.async(dispatcher, CoroutineStart.LAZY) {
- KtxAsync.task()
- }})
- fun Deferred<Any>.startIf(predicate: ()->Boolean) = apply {
- if(!isActive && predicate()) start()
- }
- fun Deferred<Any>.resultIfElse(predicate: ()->Boolean, action: ()-> Any? = {null}): Any? {
- val def = this
- var result: Any? = null
- KtxAsync.launch(Dispatchers.Unconfined) {
- result = if(def.isCompleted && predicate()) def.await() else action()
- }
- return result
- }
- fun Deferred<Any>.remove(name: String = "Default") = apply {
- if(isCompleted) asyncMap.remove(name)
- }
Advertisement
Add Comment
Please, Sign In to add comment