I’ve got a function like so: ``` suspend fun ge...
# coroutines
t
I’ve got a function like so:
Copy code
suspend fun getAudio(songId: Long): AudioStream? {
        return withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            songRepository.getSongs(SongQuery.SongIds(listOf(songId))).firstOrNull()?.firstOrNull()?.let { song ->
                val uri = Uri.parse(song.path)
                if (song.path.startsWith("content://")) {
                    if (DocumentsContract.isDocumentUri(context, uri)) {
                        val documentFile = DocumentFile.fromSingleUri(context, uri)
                        documentFile?.let {
                            context.contentResolver.openInputStream(documentFile.uri)?.let { inputStream ->
                                AudioStream(inputStream, documentFile.length(), documentFile.type ?: "audio/*")
                            }
                        }
                    } else {
                        context.contentResolver.openInputStream(uri)?.let { inputStream ->
                            AudioStream(inputStream, song.size, song.mimeType)
                        }
                    }
                } else {
                    AudioStream(File(uri.toString()).inputStream(), song.size, song.mimeType)
                }
            }
        }
    }
AS complains that
openInputStream()
is an ‘inappropriate blocking call’ Is this a false positive by AS, or am I doing something wrong here?
e
TL;DR But I've seen this warning before. It is inappropriate to block a thread like this. Without reading your code, I assume that you're calling the blocking function from a coroutine using the IO dispatcher? Because the function is blocking and not suspending, it will block the thread used by the dispatcher nonetheless. This means that you might block other coroutine safe code that uses the same thread. If I'm not mistaken..
t
Yeah, the entire function body is wrapped in
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
. I think I understand the warning, but it seems potentially incorrect here.. I've read about this elsewhere but I don't feel confident that the code in my example is equivalent.
m
FWIW, I have seen that erroneous warning when it is not literally
withContext(<http://Dispatchers.IO|Dispatchers.IO>
). See https://issuetracker.google.com/issues/160491867 for one case that I filed, where
+
to chain
CoroutineContext
objects together confuses that inspection.
👍 1