Single Flight
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
the key type. Keys match by equals.
the result type of the work.
Functions
Returns the number of keys with a running flight, for example for logs or tests.
Returns true while a flight runs for key. The flight can end right after this returns.