https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Nikky

07/31/2020, 3:59 PM
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

streetsofboston

07/31/2020, 4:05 PM
Copy code
suspend fun fromSomeManagerCallback(): SomeResult = suspendCancellableCoroutine { cont ->
    someManager.setCallback { result ->
        cont.resume(result)
    }
}
n

Nikky

07/31/2020, 4:07 PM
thanks
s

streetsofboston

07/31/2020, 4:08 PM
Be sure that the callback, provided in the example to
setCallback
will be called no more than once.
n

Nikky

07/31/2020, 4:58 PM
what should i put for onCancellation in the resule call ?
seems like that is required.. should i just rethrow ?
s

streetsofboston

07/31/2020, 5:14 PM
If the callback also can return a Throwable, you can do
cont.resumeWithException(error)
n

Nikky

07/31/2020, 5:18 PM
i mean there seems to be no resume call without providing
onCancellation
callback
s

streetsofboston

07/31/2020, 5:51 PM
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

Nikky

07/31/2020, 7:16 PM
sometimes i really don't understand why some stuff is in extensions in the core library
s

streetsofboston

07/31/2020, 7:28 PM
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

Nikky

07/31/2020, 7:35 PM
but the default IDE settings turn wirldcard imports into specific ones
s

streetsofboston

07/31/2020, 7:44 PM
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`….
3 Views