AsyncAwait
AsyncAwait copied to clipboard
Parallel execution?
When I try to execute several tasks in parallel my code looks ugly.
async {
await {
async {
await {
async {
await {
val it = System.currentTimeMillis()
while (System.currentTimeMillis() - it < 5000);
Log.w("Executing coroutine", "Task1")
}
}
val it = System.currentTimeMillis()
while (System.currentTimeMillis() - it < 5000);
Log.w("Executing coroutine", "Task2")
}
}
val it = System.currentTimeMillis()
while(System.currentTimeMillis() - it < 5000 );
Log.w("Executing coroutine", "Task3")
}
Log.w("Executing coroutine", "All tasks completed")
}
Is any way to make parallel execution looks more elegant? Something like this
async {
awaitParallel {
val it = System.currentTimeMillis()
while (System.currentTimeMillis() - it < 5000);
Log.w("Executing coroutine", "Task1")
}
awaitParallel {
val it = System.currentTimeMillis()
while (System.currentTimeMillis() - it < 5000);
Log.w("Executing coroutine", "Task2")
}
awaitParallel {
val it = System.currentTimeMillis()
while (System.currentTimeMillis() - it < 5000);
Log.w("Executing coroutine", "Task3")
}
Log.w("Executing coroutine", "All tasks completed")
}
It should be possible like this
async {
await { }
}
async {
await { }
}
but for the current version, all await
blocks will be executed sequentially.
This happens because we create one SingleThreadExecutor
per async
's target instance. The async
function is an extension function for Any
class and so that Any instance is considered as a target object.
https://github.com/metalabdesign/AsyncAwait/blob/master/asyncawait/src/main/kotlin/co/metalab/asyncawait/Async.kt#L247
E.g. if you place subsequent async calls in your Activity - the only one await block is executed at the same time as activity instance is a target for both async
calls.
The not recommended workaround, for now, could be to run async blocks on any other target (your implementation used similar approach)
Any().async {
await { }
}
Any().async {
await { }
}
We should add an API for parallel executions.