-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1-object.kt
More file actions
56 lines (46 loc) · 1.24 KB
/
1-object.kt
File metadata and controls
56 lines (46 loc) · 1.24 KB
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
53
54
55
56
package Deferred
import kotlinx.coroutines.*
interface PrimaryDeferred<T> {
fun done(callback: (T) -> Unit): PrimaryDeferred<T>
fun resolve(data: T): PrimaryDeferred<T>
}
private fun <T: Any> asyncResult() = object: PrimaryDeferred<T> {
private lateinit var value: T
private var onDone: ((T) -> Unit)? = null
override fun done(callback: (T) -> Unit): PrimaryDeferred<T> {
onDone = callback
return this
}
override fun resolve(data: T): PrimaryDeferred<T> {
value = data
onDone?.invoke(value)
return this
}
}
private fun main() = runBlocking {
val persons = mapOf(
10 to "Marcus Aurelius",
11 to "Mao Zedong",
12 to "Rene Descartes"
).withDefault { "" }
fun getPerson(id: Int): PrimaryDeferred<String> {
val result = asyncResult<String>()
GlobalScope.launch {
delay(1000)
result.resolve(persons.getValue(id))
}
return result
}
val d1 = getPerson(10)
d1.done { value ->
println("value d1: $value")
}
val d2 = getPerson(11)
GlobalScope.launch {
delay(1500)
d2.done { value ->
println("value d2: $value")
}
}
delay(2000)
}