Created
April 30, 2018 15:49
-
-
Save mrmitew/55ebe1c3cbbec291dbe79f09165b7297 to your computer and use it in GitHub Desktop.
In-flight job caching with cancellation support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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