Created
March 9, 2018 10:05
-
-
Save elizarov/eb77d7eb17888764f57f07465482006e to your computer and use it in GitHub Desktop.
Kotlin Coroutines, a deeper look
This file contains hidden or 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
// Inspired by http://akarnokd.blogspot.ru/2017/09/rxjava-vs-kotlin-coroutines-quick-look.html | |
// Requires Kotlin 1.2.30 or later | |
// Uses kotlinx.coroutines library | |
import kotlinx.coroutines.experimental.* | |
import kotlin.system.* | |
suspend fun f1(i: Int): Int { | |
println("f1 attempt $i") | |
delay(if (i != 3) 2000 else 200) | |
return 1 | |
} | |
suspend fun f2(i: Int): Int { | |
println("f2 attempt $i") | |
delay(if (i != 3) 2000 else 200) | |
return 2 | |
} | |
suspend fun <T> retry(block: suspend (Int) -> T): T { | |
for (i in 1..5) { // try 5 times | |
try { | |
return withTimeout(500) { // with timeout | |
block(i) | |
} | |
} catch (e: TimeoutCancellationException) { /* retry */ } | |
} | |
return block(0) // last time just invoke without timeout | |
} | |
fun main(args: Array<String>) = runBlocking { | |
val time = measureTimeMillis { | |
val v1 = async { retry { f1(it) } } | |
val v2 = async { retry { f2(it) } } | |
println("Result = ${v1.await() + v2.await()}") | |
} | |
println("Completed in $time ms") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment