Skip to content

Commit a1e2985

Browse files
committed
grpc-native: Add callback future
Signed-off-by: Johannes Zottele <[email protected]>
1 parent 751308d commit a1e2985

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Copyright 2023-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package kotlinx.rpc.grpc.internal
6+
7+
import kotlinx.atomicfu.atomic
8+
9+
internal class CallbackFuture<T : Any> {
10+
private val value = atomic<T?>(null)
11+
private val callback = atomic<((T) -> Unit)?>(null)
12+
13+
fun complete(result: T) {
14+
if (value.compareAndSet(null, result)) {
15+
callback.getAndSet(null)?.invoke(result)
16+
} else {
17+
error("Already completed")
18+
}
19+
}
20+
21+
fun onComplete(cb: (T) -> Unit) {
22+
val r = value.value
23+
if (r != null) cb(r)
24+
else if (!callback.compareAndSet(null, cb)) {
25+
// Already someone registered → run immediately
26+
value.value?.let(cb)
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)