Skip to content

Instantly share code, notes, and snippets.

@elizarov
Last active September 21, 2019 16:15
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/f51db8d3b64b4b15a1eb029b2ae01b13 to your computer and use it in GitHub Desktop.
Save elizarov/f51db8d3b64b4b15a1eb029b2ae01b13 to your computer and use it in GitHub Desktop.
// https://akarnokd.blogspot.ru/2017/09/rxjava-vs-kotlin-coroutines-quick-look.html
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
}
suspend fun coroutineWay() {
val t0 = System.currentTimeMillis()
repeat(3) { i ->
println("Attempt ${i + 1} at T=${System.currentTimeMillis() - t0}")
val v1 = async(CommonPool) { f1(i) }
val v2 = async(CommonPool) { f2(i) }
withTimeoutOrNull(500) {
val r1 = v1.await()
val r2 = v2.await()
r1 + r2
}?.let { sum ->
println(sum)
println("End at T=${System.currentTimeMillis() - t0}")
return // success, may return computed sum
}
println("Timeout at T=${System.currentTimeMillis() - t0}")
}
error("Too many attempts, operation aborted")
}
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