https://kotlinlang.org logo
#android
Title
# android
m

Márton Matusek

03/18/2024, 11:02 AM
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

Gautam Lad

03/18/2024, 11:47 AM
Wrap the function that has a callback with a
suspendCoroutune
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/suspend-coroutine.html
☝️ 1
m

Márton Matusek

03/18/2024, 3:24 PM
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
Or any coroutine scope, including custom ones. Depends on where the callback is
2 Views