Created
September 6, 2017 22:25
-
-
Save elizarov/13902a1844e964a4793a54a58c00f50d to your computer and use it in GitHub Desktop.
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
// 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