Futures, cancellation and coroutines

fun doSomethingAsync(): CompletableFuture<SomeData>
val futureOne = doSomethingAsync()
val two = doSomethingElse() // while doSomethingAsync is working
futureOne.whenComplete { /* process success or failure */ }
doSomethingAsync().thenAcceptBoth(CompletableFuture.supplyAsync {
doSomethingElse()
}) { one, two ->
// combine results of both calls here
}.whenComplete { /* process success or failure */ }
fun doBothAsync(): CompletableFuture<SomeOtherResult> =
doSomethingAsync()
.thenAcceptBoth(doSomethingElseAsync()) { one, two ->
// combine results of both calls here
}
fun doSequentiallyAsync(): CompletableFuture<SomeOtherResult> =
doSomethingAsync().
thenCompose { something ->
doSomethingElseAsync(something)
}
suspend fun doSomething(): SomeData
suspend fun doSequentially() {
val something = doSomething()
doSomethingElse(something)
}
suspend fun doBoth() = coroutineScope {
val
deferredOne = async { doSomething() }
val
two = doSomethingElse() // while doSomething is working
val one = deferredOne.await()
// combine results of both calls here
}
val something = doSomethingAsync().await()
val value = GlobalScope.async { doSomething() }

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store