File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed
kotlinx-coroutines-jdk8/src/test/kotlin/examples Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments