Hi Everyone, Pretty beginner question regarding co...
# android
m
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!
g
Wrap the function that has a callback with a
suspendCoroutune
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/suspend-coroutine.html
☝️ 1
m
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
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
You can. Use the lifecycle scope launch method if you’d like
Or any coroutine scope, including custom ones. Depends on where the callback is