https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Colton Idle

12/23/2019, 12:08 AM
Still new with coroutines. I wrote the following code, but I get a warning that you can see in the screenshot. I'm assuming it's because nothing is telling
fromJson()
to do it's work in the background, but I don't think moshi has a suspend function for this? How would someone typically solve this?
Copy code
viewModelScope.launch {
    //Get from file

    try {
        val file = File(context.filesDir, "mycache")
        val contents = file.readText()

        val moshi = Moshi.Builder().build()
        val jsonAdapter = moshi.adapter(MyObject::class.java)
        val json = jsonAdapter.fromJson(contents)
        //DO SOMETHING
    } catch (e: Exception) {

    } finally {
    }
}
o

octylFractal

12/23/2019, 1:05 AM
wrap it in
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
although I think intellij is being fooled by
fromJson
throwing IOException, as I doubt it does IO.
file.readText()
probably does though
c

Colton Idle

12/23/2019, 1:12 AM
Any way to check, or should I be okay wrapping it with
withContext{}
?
o

octylFractal

12/23/2019, 1:48 AM
javadoc? I imagine it takes a string, so it shouldn't do IO to read, but maybe the
jsonAdapter
does other things with global state that involve IO. I would guess that's not the case though
d

Dico

12/23/2019, 2:09 AM
I would put the file reading in io scope and suppress it for fromJson
g

gildor

12/23/2019, 12:55 PM
as I doubt it does IO
This warning is about blocking operation, not about only IO. Json creation is indeed potentially long operation even if it doesn't do any IO, so it make sense and it's not fooled. Wrapping to CPU bound dispatcher is not bad idea for serialization/deserialization
c

Colton Idle

12/24/2019, 9:16 AM
@gildor should I use Dispatchers.IO or is there another I should use?
g

gildor

12/24/2019, 9:22 AM
It depends, but Dispatchers.Default should be also fine because it's CPU bound
o

octylFractal

12/24/2019, 9:40 AM
note that the warning will only go away (without suppression) if you use
<http://Dispatchers.IO|Dispatchers.IO>
iirc
5 Views