CoalescingTaskRunner

class CoalescingTaskRunner(context: <Error class: unknown class> = Dispatchers.Default, errorHandler: (Throwable) -> Unit = {}, task: suspend () -> Unit)

A coroutine-based utility that coalesces multiple trigger calls into at most one active execution of a suspending task. It runs the task in a dedicated coroutine and ensures that:

  • Only one instance of task runs at a time.

  • If schedule is called while the task is running, the task is scheduled to run once more after the current execution finishes.

  • Repeated calls to schedule while the task is running are coalesced into a single extra run.

This is useful for scenarios like batching updates or refreshing state from external sources, where overlapping invocations should not stack up but a final follow-up call should be ensured.

Example:

val runner = CoalescingTaskRunner(context = Dispatchers.Default) {
println("Running update")
delay(1000)
}

repeat(10) { runner.schedule() } // Will run at most twice

runner.close()

Parameters

context

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

errorHandler

Optional callback for handling exceptions thrown by the task.

task

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

Constructors

Link copied to clipboard
constructor(context: <Error class: unknown class> = Dispatchers.Default, errorHandler: (Throwable) -> Unit = {}, task: suspend () -> Unit)

Functions

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