Skip to content

Instantly share code, notes, and snippets.

@elizarov
Created March 9, 2018 10:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elizarov/eb77d7eb17888764f57f07465482006e to your computer and use it in GitHub Desktop.
Save elizarov/eb77d7eb17888764f57f07465482006e to your computer and use it in GitHub Desktop.
Kotlin Coroutines, a deeper look
// 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