Skip to content

Commit e921098

Browse files
committed
Allow a continuation callback to be called only once
1 parent fae41ab commit e921098

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,36 @@
11
package li.klass.fhem.util
22

3-
import kotlinx.coroutines.suspendCancellableCoroutine
3+
import org.slf4j.LoggerFactory
44
import kotlin.coroutines.resume
55
import kotlin.coroutines.resumeWithException
6+
import kotlin.coroutines.suspendCoroutine
67

78
interface Callback<T> {
89
fun onComplete(result: T)
910
fun onException(e: Exception?)
1011
}
1112

12-
suspend fun <T> awaitCallback(block: (Callback<T>) -> Unit): T =
13-
suspendCancellableCoroutine { cont ->
14-
block(object : Callback<T> {
15-
override fun onComplete(result: T) = cont.resume(result)
16-
override fun onException(e: Exception?) {
13+
suspend fun <T> awaitCallback(toExecute: (Callback<T>) -> Unit): T {
14+
return suspendCoroutine { cont ->
15+
var isResumed = false
16+
toExecute(object : Callback<T> {
17+
override fun onComplete(result: T) {
18+
if (!isResumed) {
19+
isResumed = true
20+
cont.resume(result)
21+
} else {
22+
LoggerFactory.getLogger(Callback::class.java).error("Cannot resume callback more than once (onComplete)")
23+
}
24+
}
25+
26+
override fun onException(e: Exception?) {
27+
if (!isResumed) {
28+
isResumed = true
1729
e?.let { cont.resumeWithException(it) }
30+
} else {
31+
LoggerFactory.getLogger(Callback::class.java).error("Cannot resume callback more than once (onException)")
1832
}
19-
})
20-
}
33+
}
34+
})
35+
}
36+
}

0 commit comments

Comments
 (0)