Kotlin 是否有方法捕获FlatterMerge()中抛出的异常?

Kotlin 是否有方法捕获FlatterMerge()中抛出的异常?,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,给定此代码,在getRecords()中引发的异常不会在testFlattMerge()中捕获-但它是否应该不可捕获?另外,在getPeople()中,可以捕获异常,该异常会导致flattmerge()按预期工作,但它会在打印任何数字之前打印出“捕获的人”,而不是像我预期的那样在64之后。这是正确的行为吗?我不能完全适应我的flattmerge()心理模型 import kotlin.reflect.KProperty import kotlin.system.measureTimeMillis

给定此代码,在
getRecords()
中引发的异常不会在
testFlattMerge()
中捕获-但它是否应该不可捕获?另外,在
getPeople()
中,可以捕获异常,该异常会导致
flattmerge()
按预期工作,但它会在打印任何数字之前打印出“捕获的人”,而不是像我预期的那样在64之后。这是正确的行为吗?我不能完全适应我的
flattmerge()
心理模型

import kotlin.reflect.KProperty
import kotlin.system.measureTimeMillis
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*

fun getRecords(id: Int) = flow {
    repeat(5) { emit("A record for $id") }
    if (id == 6) throw RuntimeException("Anything but #6!")
    repeat(5) { emit("A record for $id") }
}

fun getPeople() = flow {
    repeat(10) { emit(getRecords(it)) }
    // repeat(10) { emit(getRecords(it).catch{ println("Caught in getPeople()")}) } // This works, but it prints /before/ any cnt lines...?
}

suspend fun testFlattenMerge() {
    println ("Merge with flattenMerge()")
    var cnt = 0
    val flowOfFlows = getPeople()
    flowOfFlows.catch{ println("Caught before flattenMerge")}
        .flattenMerge()
        .catch{ println("Caught after flattenMerge")}
        .collect {
            println("${cnt++}") // Without catching inside getPeople() this stops at 64
        }
}

suspend fun testManualMerge() {
    println("Merge manually")
    var cnt = 0    
    repeat(10) {
        getRecords(it).catch{ println("Caught in manual merge") }
            .collect {
                println("${cnt++}") // This goes up to 94, as expected
            }
    }
}

fun main() = runBlocking {
    testFlattenMerge()
    testManualMerge()
}

Flow
仍在解决异常处理行为,这方面有几个尚未解决的问题。我想这是其中的一个,也许值得提出一个问题或检查现有的问题。我想出现64是因为它是一个内部批处理大小。根据我设计的示例,应该是64。(它在64次发射后偶然抛出)如果需要,我会在GitHub上发布<代码>流仍在解决异常处理行为,但仍有几个问题有待解决。我想这是其中的一个,也许值得提出一个问题或检查现有的问题。我想出现64是因为它是一个内部批处理大小。根据我设计的示例,应该是64。(它在64次发射后偶然抛出)如果需要,我会在GitHub上发布!