Skip to content

Commit 0764177

Browse files
committed
One more simple example with futures
1 parent 302603e commit 0764177

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package examples
2+
3+
import kotlinx.coroutines.experimental.future.await
4+
import kotlinx.coroutines.experimental.future.future
5+
import java.util.concurrent.CompletableFuture
6+
7+
fun main(args: Array<String>) {
8+
// this example shows how easy it is to perform multiple async operations with coroutines
9+
val future = future {
10+
(1..5).map { // loops are no problem at all
11+
startLongAsyncOperation(it).await() // suspend while the long method is running
12+
}.joinToString("\n")
13+
}
14+
println("We have a long-running computation in background, let's wait for its result...")
15+
println(future.get())
16+
}
17+
18+
fun startLongAsyncOperation(num: Int): CompletableFuture<String> =
19+
CompletableFuture.supplyAsync {
20+
Thread.sleep(1000L) // imitate some long-running computation, actually
21+
"$num" // and return a number converted to string
22+
}

0 commit comments

Comments
 (0)