parallel

suspend fun <T> Iterable<suspend () -> T>.parallel(concurrency: Int = Int.MAX_VALUE): List<T>(source)

Runs every suspending task concurrently and returns the results in input order.

Fail-fast: the first task failure cancels the remaining tasks and is rethrown (coroutineScope + async + awaitAll). Use supervisedAll to isolate failures.

concurrency limits how many tasks run at once (default: unlimited); it must be greater than zero.

When the caller's context has a TraceSpan, the tasks run in one child span named "parallel"; otherwise nothing changes.

Example:

val (first, second) = listOf<suspend () -> Item>({ repo.a() }, { repo.b() }).parallel()

Rules: CONCUR_003 (launch all async jobs before awaiting), SCOPE_004 (first failure cancels the rest in coroutineScope). See docs/BEST_PRACTICES_COROUTINES.md.

Requires opting in to ExperimentalStructuredCoroutines.

Receiver

the task factories to run.

Return

one result per task, in input order. An empty receiver yields an empty list.

Parameters

concurrency

maximum number of tasks running at once; must be greater than zero.

See also

Throws

the first task failure, after the remaining tasks were cancelled.

if the caller is cancelled.