在 Kotlin callbackFlow 构建器中捕获异常

问题描述

我有一个看起来像这样的消费者:

// ItemConsumer.kt
try {
    job = itemService
            .connect()
            .flowOn(Dispatchers.IO)
            .catch { e ->
                throw e
            }
            .onEach {
                // Update UI for each item collected
            }
            .launchIn(viewModelScope)
} catch (e : Exception) {
    // Handle exception
}

我有一个看起来像这样的制作人:

// ItemService.kt (Producer)
fun connect():Flow<Item> = callbackFlow {
    check(1 == 0) // This is expected to throw an IllegalStateException
}

我知道 .catch { } 将处理消费者的 .collect { } 或 .onEach { } 块中出现的任何问题。但是如何抛出在 callbackFlow { } builder 中发生的异常,以便它可以在消费者的 .catch { } 中被捕获?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)