-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFuture.kt
52 lines (40 loc) · 1.22 KB
/
Future.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright © FunctionalKotlin.com 2017. All rights reserved.
import kotlinx.coroutines.experimental.*
typealias FutureTask<A> = Deferred<A>
class Future<out A>(val task: FutureTask<A>) {
companion object
}
fun <A> Future.Companion.pure(a: A): Future<A> =
Future(async(CommonPool) { a })
fun <A> asyncFuture(getValue: () -> A): Future<A> =
Future(async(CommonPool) {
getValue()
})
fun <A> Future<A>.runAsync(onComplete: (A) -> Unit) {
launch(CommonPool) {
onComplete(task.await())
}
}
fun <A> Future<A>.runSync(): A =
runBlocking { [email protected]() }
fun <A, B> Future<A>.map(transform: (A) -> B): Future<B> =
flatMap {
Future(async(CommonPool) {
transform(it)
})
}
fun <A, B> Future<A>.flatMap(transform: (A) -> Future<B>): Future<B> =
Future(async(CommonPool) {
transform([email protected]()).task.await()
})
fun <A, B> Future<A>.apply(futureAB: Future<(A) -> B>): Future<B> =
Future(async(CommonPool) {
val a = [email protected]()
val ab = futureAB.task.await()
ab(a)
})
fun main(args: Array<String>) {
asyncFuture { 23 + 19 }
.map { it + 3 }
.runAsync(::println)
}