Skip to content

Instantly share code, notes, and snippets.

@elizarov
Created September 6, 2017 22:31
Show Gist options
  • Save elizarov/799a11783e0cfff4f14f235c966644d8 to your computer and use it in GitHub Desktop.
Save elizarov/799a11783e0cfff4f14f235c966644d8 to your computer and use it in GitHub Desktop.
// https://akarnokd.blogspot.ru/2017/09/rxjava-vs-kotlin-coroutines-quick-look.html
// Abstraction
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 */
}
fun <T> asyncRetry(n: Int, time: Long, block: suspend (Int) -> T) =
async(CommonPool) {
retry(n) { i ->
withTimeout(time) {
block(i)
}
}
}
suspend fun coroutineWay() {
val t0 = System.currentTimeMillis()
val v1 = asyncRetry(3, 500) { i -> f1(i) }
val v2 = asyncRetry(3, 500) { i -> 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()
}
@christopherperry
Copy link

Should use delay instead of Thread.sleep()

suspend fun f1(i: Int): Int {
    delay(if (i != 2) 2000L else 200L)
    return 1
}

suspend fun f2(i: Int): Int {
    delay(if (i != 2) 2000L else 200L)
    return 2
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment