我最近学会了Coroutines
,我正在尽最大努力将其应用到所有事情上。
我了解到您可以将回调转换为coroutine
。
是否可以使用 suspendCoroutine
将Broadcast Receiver
转换为coroutines
?
我该怎么做?
这里有一种方法(由 leonardkraemer 和这个答案提供):
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()
}
}