QQ: I have a Java API with a callback and I want t...
# coroutines
e
QQ: I have a Java API with a callback and I want to wrap that in a kotlin suspend function, so I can avoid callback hell What is the most idiomatic way to do that? One obvious solution is a Countdown latch, but I imagine there being something more elegant.
o
usually
suspendCancellableCoroutine
will handle most of the work for you
e.g.
Copy code
suspendCancellableCoroutine { cont ->
  javaApi.withCallback { data, err ->
    if (err != null) cont.resumeWithException(err)
    else cont.resumeWith(data)
  }
}
😍 1
e
or
callbackFlow
if the callback can be invoked multiple times
o
if you can unsubscribe/cancel on the javaApi (say it returns an Unsubscribe object or something), it's a good idea to also do
cont.invokeOnCancellation { unsusbcribe() }
👍 1
e
awesome! this was exactly what I was looking for! #solved!
This actually is more what I wanted to do:
Copy code
AmbientIndication provides @Composable { MyIndication },
That way I can easily either have NoIndication or something else 🙂