CoalescingTaskRunnerWithResult

class CoalescingTaskRunnerWithResult<T>(context: <Error class: unknown class> = Dispatchers.Default, task: suspend () -> T)

A coroutine-based utility that coalesces multiple invocations of a suspending task and ensures only the latest scheduled invocation is executed, returning its result.

This is useful in scenarios where a task may be triggered frequently (e.g., UI events, network polling), but only the most recent execution and its result are relevant.

Example use case: auto-refreshing data on user input where intermediate results can be discarded.

The task is executed on a dedicated coroutine scope with optional error handling. If a task is currently running and a new one is scheduled, the new task supersedes previous pending triggers but waits for its result.

Parameters

context

Coroutine context to run the task (defaults to Dispatchers.Default).

task

The suspending function to execute. Only one instance runs at a time.

T

The result type of the task.

Constructors

Link copied to clipboard
constructor(context: <Error class: unknown class> = Dispatchers.Default, task: suspend () -> T)

Functions

Link copied to clipboard
suspend fun close()
Link copied to clipboard
suspend fun schedule(): T
Link copied to clipboard
suspend fun <R> use(block: suspend (CoalescingTaskRunnerWithResult<T>) -> R): R