KSingleFlight

Deduplicates concurrent calls to the same async operation.

If get is called while a previous call with the same key is still in progress, all callers share the same in-flight result rather than triggering duplicate work. Once the in-flight call finishes, the next call starts a fresh execution.

Inspired by Go's singleflight package and the "single-flight" cache pattern.

val flight = SingleFlight<User>()

// Two simultaneous callers both get the same result from one API call:
coroutineScope {
val a = async { flight.get("fetch_user") { api.fetchCurrentUser() } }
val b = async { flight.get("fetch_user") { api.fetchCurrentUser() } }
// api.fetchCurrentUser() is called exactly once
assertEquals(a.await(), b.await())
}

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
suspend fun get(key: Any = Unit, block: suspend () -> T): T

Executes block or awaits an existing in-flight execution sharing the same key.