Skip to content

Instantly share code, notes, and snippets.

@mrmitew
Created April 30, 2018 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrmitew/55ebe1c3cbbec291dbe79f09165b7297 to your computer and use it in GitHub Desktop.
Save mrmitew/55ebe1c3cbbec291dbe79f09165b7297 to your computer and use it in GitHub Desktop.
In-flight job caching with cancellation support
class InFlightJobCache<T> {
private val jobs = mutableMapOf<String, Deferred<T>>()
private val mux = Mutex()
suspend fun getOrFetch(key: String, factory: suspend () -> T): Deferred<T> = mux.withLock {
val request = jobs.getOrDefault(key, async(start = CoroutineStart.LAZY) { factory() })
jobs[key] = request
return request
}
suspend fun get(key: String): Deferred<T>? = mux.withLock { jobs[key] }
suspend fun cancel(key: String): Boolean? = mux.withLock {
val result = jobs[key]?.cancel()
jobs.remove(key)
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment