Created
March 16, 2020 23:53
-
-
Save jjv360/4a9298d5051d4e7b35ee3f0576f4969e to your computer and use it in GitHub Desktop.
Kovenant utility: Promise queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ydangleapps.bluetooth | |
import nl.komponents.kovenant.* | |
import nl.komponents.kovenant.functional.bind | |
/** Queue operations */ | |
class PromiseQueue { | |
// Pending operations | |
val pendingOperations = mutableListOf<() -> Promise<Unit, Exception>>() | |
var isRunning = false | |
// Add queued operation | |
fun<V> add(callback : () -> Promise<V, Exception>) : Promise<V, Exception> { | |
// Create pending promise | |
val pending = deferred<V, Exception>() | |
// Add to list | |
pendingOperations.add { | |
// Wait for promise to complete | |
task {} bind { callback() } success { | |
pending.resolve(it) | |
} fail { | |
pending.reject(it) | |
} then {} | |
} | |
// Start if this is the first one | |
if (!isRunning) { | |
isRunning = true | |
runNextOperation() | |
} | |
// Done, wait for promise | |
return pending.promise | |
} | |
private fun runNextOperation() { | |
// Get next op | |
val next = pendingOperations.firstOrNull() | |
if (next == null) { | |
isRunning = false | |
return | |
} | |
// Remove it | |
pendingOperations.removeAt(0) | |
// Run it, wait for promise | |
next() always { | |
// Run next in the chain | |
runNextOperation() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment