Skip to content

Instantly share code, notes, and snippets.

@uzzu
Last active August 20, 2019 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uzzu/5f834353804466ff0e42531990cf1332 to your computer and use it in GitHub Desktop.
Save uzzu/5f834353804466ff0e42531990cf1332 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
class Hoge
class Fuga
@ExperimentalCoroutinesApi
suspend fun hoge(): Hoge {
println("hoge started")
delay(200)
println("hoge finished")
return Hoge()
}
@ExperimentalCoroutinesApi
suspend fun fuga(): Fuga {
println("fuga started")
delay(100)
println("fuga finished")
return Fuga()
}
fun mainNonAsync()= runBlocking<Unit> {
runCatching {
val h = hoge()
val f = fuga()
Pair(h, f)
}
.onSuccess { (h, f) ->
println("$h, $f")
}
}
fun mainAsync()= runBlocking<Unit> {
runCatching {
val h = async { hoge() }
val f = async { fuga() }
Pair(h.await(), f.await())
}
.onSuccess { (h, f) ->
println("$h, $f")
}
}
// mainNonAsync()
mainAsync()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment