File tree 1 file changed +24
-8
lines changed
app/src/main/java/li/klass/fhem/util
1 file changed +24
-8
lines changed Original file line number Diff line number Diff line change 1
1
package li.klass.fhem.util
2
2
3
- import kotlinx.coroutines.suspendCancellableCoroutine
3
+ import org.slf4j.LoggerFactory
4
4
import kotlin.coroutines.resume
5
5
import kotlin.coroutines.resumeWithException
6
+ import kotlin.coroutines.suspendCoroutine
6
7
7
8
interface Callback <T > {
8
9
fun onComplete (result : T )
9
10
fun onException (e : Exception ? )
10
11
}
11
12
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
17
29
e?.let { cont.resumeWithException(it) }
30
+ } else {
31
+ LoggerFactory .getLogger(Callback ::class .java).error(" Cannot resume callback more than once (onException)" )
18
32
}
19
- })
20
- }
33
+ }
34
+ })
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments