'不适当的阻止方法调用'-如何在Android Studio上处理此警告 [英] 'Inappropriate blocking method call' - How to handle this warning on Android Studio

查看:2616
本文介绍了'不适当的阻止方法调用'-如何在Android Studio上处理此警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了此代码段,以将图像文件从Firebase存储下载到本地存储.

I have written this code snippet to download image files from firebase storage to local storage.

contentResolver.openOutputStream(uri)?.use { ops ->   // *
    Firebase.storage.getReferenceFromUrl(model.mediaUrl).stream.await().stream.use { ips ->
        val buffer = ByteArray(1024)
        while (true) {
            val bytes = ips.read(buffer)   // *
            if (bytes == -1)
                break
            ops.write(buffer, 0, bytes)   // *
        }
    }
}

在标记的行中,android studio向我发出Inappropriate blocking method call警告,突出显示openOutputStream(),read()和write()函数.我已经运行了几次代码,并且运行正常.整个代码段都在一个挂起函数内部,可从IO CoroutineScope调用.
有人请告诉我此警告的实际原因和解决方法.

In the marked lines, android studio is giving me Inappropriate blocking method call warning, highlighting openOutputStream(), read() and write() functions. I have ran the code few times and it has worked properly. This entire code snippet is inside a suspend function, called from an IO CoroutineScope.
Someone please tell me the actual cause and solutions for this warning.

编辑.此代码在以下上下文中调用.

Edit This code is called in the following context.

fun someFunc() {
    lifecycleScope.launch(IO) {
        val uri = getUri(model)
        ...
    }
    ...
}
...
suspend fun getUri(model: Message): Uri {
    ... // Retrive the image file using mediastore.
    if ( imageNotFound ) return downloadImage(model)
    else return foundUri
}
suspend fun downloadImage(model: Message): Uri {
    ... // Create contentvalues for new image.
    val uri = contentResolver.insert(collectionUri, values)!!
    // Above mentioned code snippet is here.
    return uri
}

推荐答案

一个正确组成的暂挂函数永不阻塞.它不应该依赖于从特定的调度程序调用,而应该在适当的调度程序中显式包装阻塞代码.

A properly composed suspend function never blocks. It should not depend on being called from a specific dispatcher, but rather it should explicitly wrap blocking code in the appropriate dispatcher.

因此,应将暂挂函数中调用阻止代码的部分包装在withContext(Dispatchers.IO){}中.然后,调用它的协程甚至不需要指定调度程序.这使得使用lifecycleScope调用函数和更新UI变得非常方便,而不必担心调度程序.

So the parts of your suspend function that call blocking code should be wrapped in withContext(Dispatchers.IO){}. Then the coroutine that calls it doesn't even need to specify a dispatcher. This makes it very convenient to use lifecycleScope to call functions and update UI and never worry about dispatchers.

示例:

suspend fun foo(file: File) {
    val lines: List<String> = withContext(Dispatchers.iO) {
        file.readLines()
    }
    println("The file has ${lines.size} lines.")
}

这篇关于'不适当的阻止方法调用'-如何在Android Studio上处理此警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆