Coalescing Task Runner
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
Coroutine context to run the task (defaults to Dispatchers.Default).
Optional callback for handling exceptions thrown by the task.
The suspending function to execute. Only one instance runs at a time.