Skip to content

Instantly share code, notes, and snippets.

@jjv360
Created March 16, 2020 23:53
Show Gist options
  • Save jjv360/4a9298d5051d4e7b35ee3f0576f4969e to your computer and use it in GitHub Desktop.
Save jjv360/4a9298d5051d4e7b35ee3f0576f4969e to your computer and use it in GitHub Desktop.
Kovenant utility: Promise queue
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