Still new with coroutines. I wrote the following c...
# coroutines
c
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
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
Any way to check, or should I be okay wrapping it with
withContext{}
?
o
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
I would put the file reading in io scope and suppress it for fromJson
g
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
@gildor should I use Dispatchers.IO or is there another I should use?
g
It depends, but Dispatchers.Default should be also fine because it's CPU bound
o
note that the warning will only go away (without suppression) if you use
<http://Dispatchers.IO|Dispatchers.IO>
iirc