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

hho

05/17/2021, 12:48 PM
Hi, I've just started using coroutines… I'm trying to parse JSON (with Jackson) in a
suspend fun
, and the "Inappropriate blocking method call" inspection flags my code:
Copy code
val message = objectMapper.readTree(inputString)
What can I do about it? It's not doing I/O, it's operating on a String.
y

Yan Pujante

05/17/2021, 1:27 PM
If you use the annotation
@Suppress("UNCHECKED_CAST", "BlockingMethodInNonBlockingContext")
it will remove the warning. I assume because it is actually not blocking it is the right thing to do, but I am no expert in coroutines...
s

streetsofboston

05/17/2021, 2:01 PM
The code 'linter' assumes that any method (block of code) that throws an IOException (or a sub-class of it) is blocking. This assumption is often right but also often wrong 🙂
1
h

hho

05/17/2021, 2:11 PM
Ah, that explains it. Thank you both, I'll go with suppressing the warning for now.
g

gildor

05/18/2021, 4:12 AM
Also in this particular case it depends how big json is, it can be a heavy computation, but probably if you use string it's not so big
h

hho

05/18/2021, 8:24 AM
You're right, it's <2kB. What would be the right way to do this, if this gets larger?
g

gildor

05/18/2021, 9:12 AM
use another readTree overload and pass there Reader/InputStream and wrap this line to IO dispatcher (if this InputStream/Reader is reading from network/disk) or with Default dispatcher (if it some runtime-generated JSON, so there is a chance that CPU is bottle neck)
🙏 1
3 Views