Skip to content

Instantly share code, notes, and snippets.

@miroslavign
Forked from elizarov/Example1.kt
Created October 7, 2017 14:24
Show Gist options
  • Save miroslavign/35a8d4097416f31080c872c30d3bf6c4 to your computer and use it in GitHub Desktop.
Save miroslavign/35a8d4097416f31080c872c30d3bf6c4 to your computer and use it in GitHub Desktop.
// https://akarnokd.blogspot.ru/2017/09/rxjava-vs-kotlin-coroutines-quick-look.html
// Refactoring
import kotlinx.coroutines.experimental.*
suspend fun f1(i: Int): Int {
Thread.sleep(if (i != 2) 2000L else 200L)
return 1
}
suspend fun f2(i: Int): Int {
Thread.sleep(if (i != 2) 2000L else 200L)
return 2
}
inline fun <T> retry(n: Int, block: (Int) -> T): T {
var ex: TimeoutException? = null
repeat(n) { i ->
try { return block(i) }
catch (e: TimeoutException) {
println("Failed with $e")
ex = e
}
}
throw ex!! /* rethrow last failure */
}
suspend fun coroutineWay() {
val t0 = System.currentTimeMillis()
retry<Unit>(3) { i ->
withTimeout(500) {
println("Attempt ${i + 1} at T=${System.currentTimeMillis() - t0}")
val v1 = async(CommonPool) { f1(i) }
val v2 = async(CommonPool) { f2(i) }
val r1 = v1.await()
val r2 = v2.await()
println(r1 + r2)
println("End at T=${System.currentTimeMillis() - t0}")
}
}
}
fun main(args: Array<String>) = runBlocking {
coroutineWay()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment