alexandre mommers
10/01/2024, 1:05 PMsuspend fun myFun() {
val atomicLong = AtomicReference<Long?>(null)
externalFunctionWithCallback { value ->
atomicLong.set(value)
}
while (atomicLong.get() == null) {
yield()
}
return atomicLong.get()
}
Or may be this one
suspend fun myFun() {
val atomicLong = AtomicReference<Long?>(null)
externalFunctionWithCallback { value ->
atomicLong.set(value)
}
while (atomicLong.get() == null) {
delay(1000)
}
return atomicLong.get()
}
What do you think? The goal would be to let other coroutine run while I'm waiting somethingSam
10/01/2024, 1:06 PMsuspendCoroutine
(or suspendCancellableCoroutine
)?Joffrey
10/01/2024, 1:06 PMSam
10/01/2024, 1:08 PMsuspend fun myFun() = suspendCoroutine<Long> { cont ->
externalFunctionWithCallback { value ->
cont.resume(value)
}
}
alexandre mommers
10/01/2024, 1:09 PMJoffrey
10/01/2024, 1:09 PMsuspendCancellableCoroutine
variant to make it cooperate with coroutines cancellation:
suspend fun myFun() = suspendCancellableCoroutine<Long> { cont ->
// you could also put this after the external call depending on the API to cancel
cont.invokeOnCancellation { ...cancel/stop/cleanup code here... }
externalFunctionWithCallback { value ->
cont.resume(value)
}
}
Joffrey
10/01/2024, 1:10 PMinvokeOnCancellation
call), but if you do this, you will technically leak the non-cancelled external function call, which is probably a bad idea