SingleFlight

class SingleFlight<K, T>

Makes callers that ask for the same key at the same time share one run of the work.

A flight is one run of the block for one key. The first caller for a key starts a flight. Callers that arrive while it runs join it: they wait and get the same result or the same failure. The name comes from Go's singleflight package.

Example

val tokenFlights = SingleFlight<String, Token>()

suspend fun token(): Token =
tokenFlights.run("session") { api.refreshToken() }

// Three screens call token() at the same time. refreshToken()
// runs once, and all three get the same Token.

Compared with a cache

SingleFlight keeps nothing after a flight ends. The next call for the key starts a new flight. To keep a value, put a cache in front of it, or use suspendLazy for a single value.

Threading

All members are safe to call from any coroutine and any thread.

Type Parameters

K

the key type. Keys match by equals.

T

the result type of the work.

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
suspend fun inFlightKeyCount(): Int

Returns the number of keys with a running flight, for example for logs or tests.

Link copied to clipboard
suspend fun isInFlight(key: K): Boolean

Returns true while a flight runs for key. The flight can end right after this returns.

Link copied to clipboard
suspend fun run(key: K, block: suspend () -> T): T

Runs block for key, or joins the flight that already runs for an equal key.