所以我最近学到了Coroutines
,我正在努力将其应用于所有方面。
我希望您可以将回调转换为coroutine
。
是否可以使用Broadcast Receiver
将coroutines
转换为suspendCoroutine
?
有人可以指导我如何做吗?
答案 0 :(得分:1)
这是一种方法(由leonardkraemer和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()
}
}