Hi Everyone,
Pretty beginner question regarding coroutine usage in Android. I would like to call a suspending function from a ConnectivityManager.NetworkCallback().
What is the best way to “bridge the gap” = call a suspending function from a non-suspending callback function? Thank you!
Thank you @Gautam Lad! I am not sure that answers my question. I meant calling a suspend function from for example the onAvailable callback of the NetworkCallback.
g
Gautam Lad
03/18/2024, 9:19 PM
You could wrap the callback function in what I suggested so your code reads something like this:
Copy code
suspend fun doWork() {
val status = callbackWrappedFunction()
nextFunction()
}
suspend fun callbackWrappedFunction() = suspendCoroutine { continuation ->
// NetworkCallback handled
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
continuation.resume(true)
}
override fun onLost(network: Network) {
super.onLost(network)
continuation.resume(false)
}
}
}
suspend fun nextFunction() {
}
a
agrosner
03/18/2024, 11:46 PM
You can. Use the lifecycle scope launch method if you’d like
agrosner
03/18/2024, 11:46 PM
Or any coroutine scope, including custom ones. Depends on where the callback is