mapSequential

suspend fun <T, R> List<T>.mapSequential(transform: suspend (T) -> Result<R>): Result<List<R>>

Maps a list of items to Results and combines them sequentially.

This function processes items one by one, stopping at the first failure. All items are processed in order, making it suitable for operations that must complete sequentially (e.g., database transactions, file operations).

When to use:

  • Operations that must complete in order

  • When you need to stop on first failure

  • Sequential processing with early termination

When NOT to use:

  • For parallel processing (use async/await instead)

  • When you need all results even if some fail (use mapNotNull instead)

Example:

val items = listOf(1, 2, 3)
val results = items.mapSequential { item ->
Result.success(item * 2)
}
// Result.success([2, 4, 6])

Cancellation: if the calling coroutine is cancelled while a transform is suspended, the CancellationException is rethrown — it is never captured in the returned Result.

Return

Result containing the list of transformed values, or failure if any transform fails

Parameters

transform

Function to transform each item to a Result