产生<类型> vs频道<类型>()

时间:2019-05-22 13:27:40

标签: kotlin coroutine kotlin-coroutines kotlinx.coroutines.channels

试图了解渠道。我想频道化android BluetoothLeScanner。为什么起作用:

fun startScan(filters: List<ScanFilter>, settings: ScanSettings = defaultSettings): ReceiveChannel<ScanResult?> {
    val channel = Channel<ScanResult>()
    scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            channel.offer(result)
        }
    }
    scanner.startScan(filters, settings, scanCallback)

    return channel
}

但不是这样:

fun startScan(scope: CoroutineScope, filters: List<ScanFilter>, settings: ScanSettings = defaultSettings): ReceiveChannel<ScanResult?> = scope.produce {
    scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            offer(result)
        }
    }
    scanner.startScan(filters, settings, scanCallback)
}

它告诉我Channel was closed何时要首次呼叫offer

EDIT1 :根据文档:The channel is closed when the coroutine completes.,这很有意义。我知道我们可以将suspendCoroutineresume配合使用,一次更换callback。但是,这是一个侦听器/流情况。我不希望协程完成

1 个答案:

答案 0 :(得分:1)

使用produce,将范围引入您的频道。这意味着,可以取消生成通过通道流式传输的项目的代码。

这也意味着您的频道的生存期从produce的lambda的开头开始,直到该lambda结束为止。

在您的示例中,您的produce调用的lambda几乎立即结束,这意味着您的Channel几乎立即关闭了。

将您的代码更改为以下内容:

fun CoroutineScope.startScan(filters: List<ScanFilter>, settings: ScanSettings = defaultSettings): ReceiveChannel<ScanResult?> = produce {
    scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            offer(result)
        }
    }
    scanner.startScan(filters, settings, scanCallback)

    // now suspend this lambda forever (until its scope is canceled)
    suspendCancellableCoroutine<Nothing> { cont ->
        cont.invokeOnCancellation {
            scanner.stopScan(...)
        }
    }
}

...
val channel = scope.startScan(filter)
...
...
scope.cancel() // cancels the channel and stops the scanner.

我添加了行suspendCancellableCoroutine<Nothing> { ... },使其“永远”挂起。

更新:使用produce并以结构化方式处理错误(允许结构化并发):

fun CoroutineScope.startScan(filters: List<ScanFilter>, settings: ScanSettings = defaultSettings): ReceiveChannel<ScanResult?> = produce {
    // Suspend this lambda forever (until its scope is canceled)
    suspendCancellableCoroutine<Nothing> { cont ->
        val scanCallback = object : ScanCallback() {
            override fun onScanResult(callbackType: Int, result: ScanResult) {
                offer(result)
            }
            override fun onScanFailed(errorCode: Int) {
                cont.resumeWithException(MyScanException(errorCode))
            }
        }
        scanner.startScan(filters, settings, scanCallback)

        cont.invokeOnCancellation {
            scanner.stopScan(...)
        }
    }
}