Last couples of days ago, I had a very intresting use case while working. I wanted to queue the call of a certain api call to make sure it’s fired in sequence because it changes the data base and it’s important to fire it in sequence.
func a() async {
// …
await beCall()
}
func beCall() async {
// api call
}
Method a() can be called concurrently and can be called from more than one thread at a time but I want to make sure that the call of beCall() is excuted by order one by one.
To fix this issue, we have many approaches we can use for example AsyncStrem as a queue or even create our own queue like AsyncQueues or TaskGate.
As a solution, I like to propose a new type to be created in the stander library instead of having so many implementation for the same thing and developers don’t know which implementation to trust and use having one built in swift will be helpful.
the naming of the object is inspired from AsyncQueues we can have an object like this:
let asyncQueue = AsyncQueue()
and to queue you simply call queue method:
let asyncQueue = AsyncQueue()
func a() async {
// …
await asyncQueue.queue {
await beCall()
}
}
func beCall() async {
// api call
}
what asyncQueue.queue does is simply it will excute await beCall() if the queue is empty and if another call happened while first task isn’t finished yet, it will queue it till it’s turn come using FIFO order.
AsyncQueue should support two important things:
- task cancellation.
- priority escaltion.
For the cancellation it can be configured to have two behaviors:
- Cancel whole queue when one task is canceled
- Only cancel the task that is canceled without affecting the queue
it can be configured like so:
let asyncQueue = AsyncQueue(cancellationPolicy: .cancelWholeQueue)
or
let asyncQueue = AsyncQueue(cancellationPolicy: .cancelEffectedTaskOnly)
Side note: please suggeste some names for the enum
For the second point, if a pirority escaltion happened for one task it should escalate the pirority of all the tasks in the queue, I don’t quite sure if this is the best option.
I think there is a need to have such an object in the swift lang and I think having something like that will be apprecited a lot. What do you think ?