Created
April 15, 2019 07:06
-
-
Save Nonda95/4e0978ef9879e74869ced9d7a16ad13e to your computer and use it in GitHub Desktop.
Kotlin Coroutines PoC of Go's singleflight
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
import kotlinx.coroutines.* | |
private val deferreds = mutableMapOf<String, Deferred<*>>() | |
@Suppress("UNCHECKED_CAST") | |
fun <T> doAsync(key: String, action: suspend () -> T): Deferred<T> { | |
val deferredResult = deferreds[key]?.takeIf { it.isActive } | |
?: GlobalScope.async { action() }.also { deferreds[key] = it } | |
return deferredResult as Deferred<T> | |
} | |
fun forget(key: String) { | |
deferreds[key]?.cancel() | |
} |
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
import kotlinx.coroutines.* | |
suspend fun main() = coroutineScope { | |
val result1 = doAsync("delay") { | |
delay(500L) | |
println("Do only once") | |
1 | |
} | |
val result2 = doAsync("delay") { | |
delay(500L) | |
println("Do only once") | |
2 | |
} | |
result1.await() | |
val result3 = doAsync("delay") { | |
delay(500L) | |
println("Do once more") | |
3 | |
} | |
println("result1: ${result1.await()}, result2: ${result2.await()}, result3: ${result3.await()}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment