Kotlin Coroutines, suspend, and Java NIO

Hi,

I’m a bit confused by the mechanics of suspend funs, coroutines and non-blocking IO imported from Java. Basically I just want to read from and write to a file, but initializing a buffered reader / writer with Files.newBuffered[Reader/Writer]() is already marked as an “inappropriate blocking method call”. But maybe that’s just how it is for this specific method, I thought, so I tried the following:

val reader = GlobalScope.async(Dispatchers.IO) { Files.newBufferedReader(path, charset) }.await()

which is of course dumb, because why would you launch an async job and then await it immediately? That’s what IntelliJ tells me as well, and suggests to merge the calls to

val reader = withContext(Dispatchers.IO) { Files.newBufferedReader(path, charset) }

which makes a lot more sense, of course. But now, the newBufferedReader() call is again marked as an inappropriate blocking method call. What is the difference between the first and the second version, considering that IntelliJ suggested the second one?

On the other hand, I really just want to do super basic I/O with a file, so if I’m approaching this wrong, please tell me how to do it properly.

Thank you!

1 Like

Your second snippet is correct, the IDE isn’t all that intelligent when it comes to figuring out when it’s okay to do blocking IO.

6 Likes