asyncWithProgress

fun <T> CoroutineScope.asyncWithProgress(context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend ProgressScope.() -> T): ProgressFuture<T>

Starts a coroutine like async, and also publishes its progress as a StateFlow.

The block runs with a ProgressScope receiver. Call ProgressScope.report in it to move the bar, and ProgressScope.slice to split the bar into weighted steps. Read the bar from ProgressFuture.progress and the result from ProgressFuture.await.

Example

val opening = scope.asyncWithProgress {
val parse = slice(0.4f, "parsing") // the first 40% of the bar
val header = parseHeader { parse.report(it) }
// The last 60%. Take a slice when its step starts.
val load = slice(0.6f, "loading")
loadPages(header) { done, total -> load.report(done, total) }
}
// Prints values such as "Progress(70%, loading)".
launch { opening.progress.collect { println(it) } }
val document = opening.await()

Lifecycle of the bar

MomentProgressFuture.progress
StartProgress(null), indeterminate
Success1f, with the last phase. You do not need a final report(1f).
Failure or cancellationthe last value, frozen

Parameters

context

added to the context of the new coroutine, as in async.

start

when the coroutine starts, as in async.

block

the operation. Its return value is the result of ProgressFuture.await.

See also