I've got some tricky Android callbacks (two successive optional auth steps with user interaction) and I'm trying to convert them to simple suspending functions.
So I started with suspendCoroutine
and was able to make the first one work. Yay!
But the second one needs to call the first. And it doesn't seem like this is the "normal" way to do things, because I can't call the first suspending function from the second. Even if I wrap it in a "launch" or "runBlocking" it still warns that I'm doing it poorly.
"Ambiguous coroutineContext due to CoroutineScope receiver of suspend function" (maybe this?)
Normally when Kotlin gets this confusing, it is because I'm making bad architecture choices! How can I make nested suspend fun(ctions)?
Pun intended.
These suspend functions you're describing sound like they do sequential actions. They shouldn't need to launch new coroutines. Nothing needs to be "nested". It should looks something like this (contrived example of two different callbacks that return a string):
suspend fun SomeClass.doSomething(msg: String): String =
suspendCoroutine { cont ->
doSomething(msg, object: SomeCallback1 {
override fun onFinished(result: String) {
cont.resume(msg)
}
})
}
suspend fun SomeClass.doSomethingElse(msg: String): String =
suspendCoroutine { cont ->
doSomethingElse(msg, object: SomeCallback2 {
override fun onFinished(result: String) {
cont.resume(msg)
}
})
}
suspend fun SomeClass.doBothThingsInSuccession(msg: String): String {
val firstResult = doSomething(msg)
return doSomethingElse(firstResult)
}
If you're trying to hide the details, those first two suspend functions can be private. Or you can combine everything into one function:
suspend fun SomeClass.doBothThingsInSuccession(msg: String): String {
val firstResult: String = suspendCoroutine { cont ->
doSomething(msg, object: SomeCallback1 {
override fun onFinished(result: String) {
cont.resume(result)
}
})
}
return suspendCoroutine { cont ->
doSomethingElse(firstResult, object: SomeCallback2 {
override fun onFinished(result: String) {
cont.resume(result)
}
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With