作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下类(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
而不是它,这将构成不适当的阻止。
withContext(IO)
内也会标记 IO 调用。 .
关于Android 和 Kotlin 协程 : inappropriate blocking method call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684138/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!