Repository of Coroutine powered data structures.
The CoroutineQueue is the flagship module of this repository. It organizes Kotlin Coroutines with a Queue.
There are ideas for additional data structures, but there is no need for them yet.
The CoroutineQueue is a simple yet powerful class designed to manage and execute coroutines in a queue-like manner. It offers several convenient methods for adding, removing, and executing tasks asynchronously using Kotlin coroutines. This library can be used in Android or any other platform supporting Kotlin coroutines.
To use the CoroutineQueue, first add the following dependency to your project's build.gradle file:
implementation "io.github.dk96-os.coroutines:queue:<latest>"After adding the dependency, you can use the CoroutineQueue class in your Kotlin code as shown below:
To add tasks to the queue, use the add method of the CoroutineQueue instance. This method takes a Deferred<T> object that represents a coroutine result.
// Create an instance of CoroutineQueue
val queue = CoroutineQueue<Int>()
// Create a new coroutine
val task1 = async { /* ...do some work... */ }
// Add the coroutine to the queue
queue.add(task1)
// Simplify
queue.add(async { /* ...do some work... */ })To cancel tasks in the queue, use the cancel method of the CoroutineQueue instance. This method cancels all currently pending coroutines in the queue and returns the number of cancelled coroutines.
// val queue = CoroutineQueue()
val cancelCount = queue.cancel()After constructing an instance, you can access the following regular methods.
add(): Booleancancel(): IntgetCount(): IntgetCapacity(): Int
To obtain the Coroutine results from the queue, you will need to use the following suspending methods.
Note: These will suspend until the requested coroutines finish, or the queue becomes empty.
suspend awaitNext(): Tsuspend awaitList(limit: Int = 0): List<T>suspend awaitAll(limit: Int = 0): Int
Retrieves the next coroutine from the queue, and waits on it's Deferred result.
- Returns the coroutine result.
Retrieves a list of coroutine results from the queue, with an optional size limit parameter.
- Returns a list of coroutine results.
Waits for all coroutines in the queue to finish, or an optional number of coroutines.
- Returns the number of coroutines waited for.
CoroutineQueue also provides convenient methods for processing items in a List or an array.
suspend transformList(input: List<A>, transform: (A) -> B?): ArrayList<B>suspend transformArray(input: Array<A>, transform: (A) -> B?): ArrayList<B>
Both methods construct their own fixed size CoroutineQueue instances to process the input, and both return an ArrayList of the transformed data.