i have to use a rather terrible java api thats bas...
# coroutines
n
i have to use a rather terrible java api thats basically 1. set callback 2. call function and the callback gives me the return value how can i wrap such a structure in a
suspend fun
?
s
Copy code
suspend fun fromSomeManagerCallback(): SomeResult = suspendCancellableCoroutine { cont ->
    someManager.setCallback { result ->
        cont.resume(result)
    }
}
n
thanks
s
Be sure that the callback, provided in the example to
setCallback
will be called no more than once.
n
what should i put for onCancellation in the resule call ?
seems like that is required.. should i just rethrow ?
s
If the callback also can return a Throwable, you can do
cont.resumeWithException(error)
n
i mean there seems to be no resume call without providing
onCancellation
callback
s
I don’t understand…. You mean an
onCancellation
callback to the
someManager
in my example-snippet?
The call to
cont.resume
just needs one parameter; the result value (an instance of
SomeResult
in my example-snippet).
I see… there are two overloaded versions of
resume
on a
Continuation
. Use the one that does not have the
onCancellation
parameter. It is the one that is an extension function on Continuation:
Copy code
public inline fun <T> Continuation<T>.resume(value: T): Unit
n
sometimes i really don't understand why some stuff is in extensions in the core library
s
Yup…. This keeps happening, made worse by non-wildcard imports that most folks use. If wildcard imports were used, the compiler would prioritize extension functions over class members (in this case, the auto-complete would have given you the extension function initially). IIRC, this will change and improve a bit in a near future version of Kotlin, where if an overloaded extension function exists for a given receiver in addition to a class method, the extension function will be the first one being suggested.
n
but the default IDE settings turn wirldcard imports into specific ones
s
I know… frustrating. Hopefully, regardless of the import settings of the IDE, that new version of the Kotlin plugin will makes things a bit better. Same issue holds for the
collect
function on a `Flow`….