异常后如何恢复流程

goo*_*man 9 kotlin kotlin-coroutines kotlin-flow

我有以下代码:

val channel = BroadcastChannel<Event>(10)

fun setup() {
    scope.launch {
        channel.asFlow().
            .flatMapLatest { fetchSomeData() }
            .catch { emit(DefaultData()) }
            .onEach { handleData() }
            .collect()

    }
}

fun load() {
    channel.offer(Event.Load)      
}
Run Code Online (Sandbox Code Playgroud)

如果fetchSomeData因异常而失败,它将被捕获catch并传递一些默认数据。问题是流本身被取消并从频道的订阅者中删除。这意味着提供给频道的任何新事件都将被忽略,因为不再有任何订阅者。

有没有办法确保在发生异常时流不会被取消?

gil*_*dor 5

您应该捕获 fetchSomeData() 的异常,因此catch从主流程移动到 fetchSomeData():

    scope.launch {
        channel.asFlow().
            .flatMapLatest { fetchSomeData().catch { emit(DefaultData()} }
            .onEach { handleData() }
            .collect()

    }
Run Code Online (Sandbox Code Playgroud)