gpt4 book ai didi

Android 和 Kotlin 协程 : inappropriate blocking method call

转载 作者:行者123 更新时间:2023-12-01 09:41:38 25 4
gpt4 key购买 nike

我有以下类(class):

class Repository(
private val assetManager: AssetManager,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
suspend fun fetchHeritagesList(): HeritageResponse = withContext(ioDispatcher) {
try {
// TODO Blocking method call?
val bufferReader = assetManager.open("heritages.json").bufferedReader()
...

我想知道为什么我会在 open("heritages.json") 中收到警告说 Innapropriate blocking method call ?不是 withContext(ioDispatcher)解决这个问题?

感谢您的解释!

最佳答案

在可挂起函数中寻找阻塞调用的 IntelliJ 检测功能不够强大,无法查看 Dispatchers.IO 之间的间接级别。及其在 withContext 中的用法.这是该问题的最小复制器:

class IoTest {
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO

suspend fun indirectRef() = withContext(ioDispatcher) {
FileInputStream(File("dummy.txt")) // Flagged as inappropriate blocking call
}

suspend fun directRef() = withContext(Dispatchers.IO) {
FileInputStream(File("dummy.txt")) // Not flagged
}
}
但是,与我的情况不同的是,您的 ioDispatcher通过构造函数公开注入(inject),因此您可以轻松提供 Dispatchers.Main而不是它,这将构成不适当的阻止。
不幸的是,我还没有听说过任何方式将调度程序的契约(Contract)正式指定为“容忍阻塞调用”,以便您可以在构造函数中强制执行它。
YouTrack 上已经有一个类似的问题开放。 .
编辑:从 2022 年 3 月 16 日的构建开始,似乎存在一种回归,即使在 withContext(IO) 内也会标记 IO 调用。 .

关于Android 和 Kotlin 协程 : inappropriate blocking method call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com