-
-
Save djodjoni/26bf8454ea6c30b2db7c22aae73d38d2 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