我最近学习了Coroutines
,我正在尽我最大的努力将它应用到所有的东西上。
我了解到可以将回调转换为coroutine
。
是否可以使用suspendCoroutine
将Broadcast Receiver
转换为coroutines
我该怎么做呢?
发布于 2019-06-12 23:20:38
以下是一种方法(由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()
}
}
https://stackoverflow.com/questions/54002646
复制相似问题