Last active
September 21, 2019 16:15
-
-
Save elizarov/f51db8d3b64b4b15a1eb029b2ae01b13 to your computer and use it in GitHub Desktop.
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
// 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