Skip to content

Commit 302603e

Browse files
committed
A couple of trivial examples with futures
1 parent 6f82783 commit 302603e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package examples
2+
3+
import kotlinx.coroutines.experimental.future.await
4+
import kotlinx.coroutines.experimental.runBlocking
5+
import java.util.concurrent.CompletableFuture
6+
7+
fun main(args: Array<String>) {
8+
// Let's assume that we have a future coming from some 3rd party API
9+
val future: CompletableFuture<Int> = CompletableFuture.supplyAsync {
10+
Thread.sleep(1000L) // imitate some long-running computation, actually
11+
42
12+
}
13+
// now let's launch a coroutine and await for this future inside it
14+
runBlocking {
15+
println("We can do something else, while we are waiting for future...")
16+
println("We've got ${future.await()} from the future!")
17+
}
18+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package examples
2+
3+
import kotlinx.coroutines.experimental.delay
4+
import kotlinx.coroutines.experimental.future.future
5+
import java.util.concurrent.CompletableFuture
6+
import java.util.concurrent.TimeUnit
7+
8+
// this function returns a CompletableFuture using Kotlin coroutines
9+
fun supplyTheAnswerAsync(): CompletableFuture<Int> = future {
10+
println("We might be doing some asynchronous IO here or something else...")
11+
delay(1, TimeUnit.SECONDS) // just do a non-blocking delay
12+
42 // The answer!
13+
}
14+
15+
fun main(args: Array<String>) {
16+
// We can use `supplyTheAnswerAsync` just like any other future-supplier function
17+
val future = supplyTheAnswerAsync()
18+
println("The answer is ${future.get()}")
19+
}

0 commit comments

Comments
 (0)