【问题标题】:Kotlin multiplatform: JobCancellationException: Parent job is CompletedKotlin 多平台:JobCancellationException:父作业已完成
【发布时间】:2021-04-23 04:57:32
【问题描述】:

我尝试编写一个使用 ktor 的 kotlin 多平台库(android 和 ios)。因此,我在使用 kotlins 协程时遇到了一些问题:

When writing tests I always get kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=JobImpl{Completed}@... exception.

我使用 ktors 模拟引擎进行测试:

client = HttpClient(MockEngine) 
{
    engine 
    {
         addHandler 
         { request ->
             // Create response object
         }
     }
}

使用 ktor 的示例方法(commonMain 模块)。我的库中的所有方法都以类似的方式编写。如果调用 client.get,则会发生异常。

suspend fun getData(): Either<Exception, String> = coroutineScope 
{
     // Exception occurs in this line:
     val response: HttpResponse = client.get { url("https://www.google.com") }

     return if (response.status == HttpStatusCode.OK) 
     {
         (response.readText() as T).right()
     } 
     else 
     {
        Exception("Error").left()
     }
}

上述方法的示例单元测试(commonTest 模块)。由于之前抛出异常,因此从未调用过 assertTrue 语句。

@Test
fun getDataTest() = runTest 
{
    val result = getData()
    assertTrue(result.isRight())
}

runTest 在 androidTest 和 iosTest 模块中的实际实现。

actual fun<T> runTest(block: suspend () -> T) { runBlocking { block() } }

我想当我使用 coroutineScope 时,它会等到所有子协程完成。我做错了什么,如何解决这个异常?

【问题讨论】:

  • 你找到解决办法了吗?
  • 协程范围,据我所知,将取消其他协程。如果您想将父作业与其他作业解耦,可以使用 CoroutineScope.launch,或者使用主管范围调用调用

标签: kotlin kotlin-coroutines ktor


【解决方案1】:

必须更新库,此故障在此处的修复报告中:https://newreleases.io/project/github/ktorio/ktor/release/1.6.1

【讨论】:

  • 绝对为我修复了它,来自版本 1.5.2
  • 乐于助人
【解决方案2】:

问题是您不能使用相同的 HttpClient 实例。我的ej:

HttpClient(CIO) {
                install(JsonFeature) {
                    serializer = GsonSerializer()
                }
            }.use { client ->
                return@use client.request("URL") {
                    method = HttpMethod.Get
                }
            }

【讨论】:

    【解决方案3】:

    CIO 的 HttpClient 不能缓存在客户端变量中并重用,最好在你的实现中更改以下代码。

    val client:HttpClient get() = HttpClient(MockEngine) {
        engine {
             addHandler { request ->
                 // Create response object
             }
         }
    }
    

    【讨论】:

    • 不清楚。提供更多信息
    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 2015-11-11
    • 2011-11-17
    • 2020-09-05
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多