Is it possible to convert BroadcastReceiver to Coroutines?

Viewed 3560

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?

1 Answers

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()
    }
}
Related