【问题标题】:Should runBlocking only be used for tests and in main function?runBlocking 是否应该仅用于测试和主要功能?
【发布时间】:2021-11-14 21:19:47
【问题描述】:

我对定期调用的函数有这个要求:

1. Get some input
2. Do 8 independent computations based on the input
3. Merge the results from these 8 computations and output the merged result

由于我至少有 8 个处理器,我可以并行执行 8 个独立计算。所以我创建了以下函数:

fun process(in: InputType): ResultType {
    runBlocking(Dispatchers.Default) {
        val jobs = in.splitToList().map { async { processItem(it) } }
        return jobs.awaitAll()
    }
}

但是,我在documentation of runBlocking 中读到它是“用于主要功能和测试”。

此函数不是主函数,而是在应用程序的调用层次结构中向下调用,该应用程序不会在其他任何地方使用协程。

如果我不应该使用 runBlocking,我应该使用什么来实现此要求?

【问题讨论】:

标签: kotlin kotlin-coroutines


【解决方案1】:

像这样使用runBlocking() 并没有错。要点是不要过度使用runBlocking() 作为将常规代码转换为协程代码的廉价方法。当转换为协程时,在我们的代码中随处放置runBlocking() 可能很诱人,仅此而已。这是错误的,因为它忽略了结构化并发,并且我们冒着阻塞不应阻塞的线程的风险。

但是,如果我们整个应用程序不是基于协程,我们只需要在某个地方使用它们,并且我们永远不需要取消后台任务,那么我认为runBlocking() 就可以了。

另一种方法是创建CoroutineScope 并将其保存在具有明确定义的生命周期的某些服务中。然后我们就可以轻松管理后台任务,取消它们等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-13
    • 2022-12-17
    • 2015-08-28
    • 2017-12-27
    • 2019-01-11
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多