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

Alexey Pushkarev

11/25/2018, 9:01 PM
Hi everyone! Could someone please explain me why I can't call one suspend function inside another ?
d

dewildte

11/25/2018, 9:05 PM
That's odd, you could async/await the return of
connectService()
but that seems wrong too.
Why exactly are you using
suspendKoroutine
?
a

Alexey Pushkarev

11/25/2018, 9:07 PM
because I just want to wrap callbacks
async/await doesn't solve the problem. It tells me the same thing about body.
d

dewildte

11/25/2018, 9:08 PM
Could you make
connectService()
an extension function of
CoroutineScope
?
a

Alexey Pushkarev

11/25/2018, 9:09 PM
hm, but why?
d

dewildte

11/25/2018, 9:10 PM
It's easier?
And you don't get this obscure error?
Ignore me I am not familiar with the
suspendKoroutine
API.
a

Alexey Pushkarev

11/25/2018, 9:14 PM
ok, no problem.
d

Dico

11/25/2018, 9:14 PM
suspendCoroutine takes a lambda parameter that accepts the continuation. The continuation must be scheduled to be called inside the lambda.
You're working with low level coroutine api here
a

Alexey Pushkarev

11/25/2018, 9:15 PM
yeah, because I want to hide callback hell with it.
d

Dico

11/25/2018, 9:16 PM
Yeah, just unwrap the suspendCoroutine call
You don't need to schedule the continuation in some special way using the api in your use case
a

Alexey Pushkarev

11/25/2018, 9:17 PM
how to unwrap it?
d

Dico

11/25/2018, 9:17 PM
Take the content of the lambda and make it the function body
Write the code in a single threaded style
The callbacks will get added by the compiler when you call suspend functions, basically
a

Alexey Pushkarev

11/25/2018, 9:19 PM
Probably, you mean that I should remove suspendCoroutine from
connectService()
, right?
d

Dico

11/25/2018, 9:19 PM
I think I have too little context to answer that
I'm talking about the bottom most function
a

Alexey Pushkarev

11/25/2018, 9:21 PM
ah, sorry you haven't seen the whole method
the code is messy, but at the first point I am gonna make it work )
b

bdawg.io

11/25/2018, 9:36 PM
Check if the billing client isn’t ready first (and call
connectService()
if not), then invoke the suspend coroutine
Copy code
suspend fun doSomethingAsync(...) {
    if (!billingClient.isReady) { connectService() }
    return suspendCoroutine<List<SkuDetails>> { cont -> ... }
}
a

Alexey Pushkarev

11/25/2018, 9:40 PM
@bdawg.io yeah, I have recently tried such way. Probably works! Thanks anyway)
u

uli

11/25/2018, 11:51 PM
I think the responsibility of this method should only be the wrapping of you callback api. I'd factor everything else (connectService,param building) out into a suspende function based on this one
1
6 Views