diff --git a/chat-android/src/main/java/com/ably/chat/PriorityExecutor.kt b/chat-android/src/main/java/com/ably/chat/PriorityExecutor.kt index f5d5b94e..0ab46f3b 100644 --- a/chat-android/src/main/java/com/ably/chat/PriorityExecutor.kt +++ b/chat-android/src/main/java/com/ably/chat/PriorityExecutor.kt @@ -6,12 +6,12 @@ import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch -private class OrderedCoroutine( +private class Task( private val priority: Int, - val suspendedFn: suspend CoroutineScope.() -> Any, + val coroutineBlock: suspend CoroutineScope.() -> Any, val resultChannel: Channel>) - : Comparable { - override fun compareTo(other: OrderedCoroutine): Int { + : Comparable { + override fun compareTo(other: Task): Int { return other.priority - this.priority } } @@ -22,21 +22,21 @@ private class OrderedCoroutine( */ class PriorityExecutor(private val scope: CoroutineScope) { private var isRunning = false - private val priorityQueue: PriorityQueue = PriorityQueue() + private val priorityQueue: PriorityQueue = PriorityQueue() - suspend fun execute(priority:Int, suspendedFun: suspend CoroutineScope.() -> T) : Channel> { + suspend fun execute(priority:Int, coroutineBlock: suspend CoroutineScope.() -> T) : Channel> { // Size of resultChannel is set to 1 to keep while loop running. - // i.e. If other end doesn't call receive on the channel, loop will be blocked. + // i.e. If caller doesn't explicitly receive on the channel, loop will be blocked. val resultChannel = Channel>(1) - priorityQueue.add(OrderedCoroutine(priority, suspendedFun, resultChannel)) + priorityQueue.add(Task(priority, coroutineBlock, resultChannel)) scope.launch { if (!isRunning) { isRunning = true while (priorityQueue.size > 0) { - val runningCoroutine = priorityQueue.remove() - val result = kotlin.runCatching { scope.async(block = runningCoroutine.suspendedFn).await() } - runningCoroutine.resultChannel.send(result) + val task = priorityQueue.remove() + val result = kotlin.runCatching { scope.async(block = task.coroutineBlock).await() } + task.resultChannel.send(result) } isRunning = false }