3

I recently learned Coroutines and I am trying my best to implement it to everything.

I learned you could convert a callback to a coroutine.

Is it possible to convert a Broadcast Receiver to coroutines by using suspendCoroutine?

How do I do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107
  • 1
    The problem is that it's fully different things. Maybe your question is about how to make something in background in broadcast receiver? – HeyAlex Jan 06 '19 at 18:38
  • 1
    I see two options: 1) Use `GlobalScope.launch{}`. This way `BroadcastReceiver.onReceive` will return immediately and die, but `GlobalScope` will live on until app process dies (when?) 2) Start `IntentService` and start blocking Coroutine in IntentService, because `IntentService` runs on background thread – Jemshit Aug 21 '20 at 10:51
  • I'm fairly new to coroutines as well, but would it work to use runBlocking inside the onReceive function? – Brill Pappin Dec 01 '20 at 14:06

1 Answers1

3

Here is one way (courtesy of leonardkraemer and this answer):

suspend fun Context.getCurrentScanResults(): List<ScanResult> {
    val wifiManager = getSystemService(Context.WIFI_SERVICE) as? WifiManager ?: return listOf()
    return suspendCancellableCoroutine { continuation ->
        val wifiScanReceiver = object : BroadcastReceiver() {
            override fun onReceive(c: Context, intent: Intent) {
                if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
                    unregisterReceiver(this)
                    continuation.resume(wifiManager.scanResults)
                }
            }
        }
        continuation.invokeOnCancellation {
            unregisterReceiver(wifiScanReceiver)
        }
        registerReceiver(wifiScanReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
        wifiManager.startScan()
    }
}
fal
  • 2,997
  • 1
  • 22
  • 13