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

diesieben07

12/13/2017, 1:20 AM
But if you need to access blocking I/O, do not do it in a coroutine.
a

asad.awadia

12/13/2017, 1:51 AM
Why not? And how else would you do it? Have two files being read in two coroutines separately? That's bad?
g

gildor

12/13/2017, 2:37 AM
You can wrap blocking code to coroutines with own thread pool. After that you can use it easily with coroutines. And database io is good example where this technique will work
w

withoutclass

12/13/2017, 3:26 AM
you could do it with builders as well using the DbPool from above
Copy code
fun sqlQuery(query: String): Deferred<DbResult> {
    return async(BdPool) {  blockingSqlQuery(query)  }
}
g

gildor

12/13/2017, 3:43 AM
I prefer suspend function in this case (easier to use). But version with
async
also useful in some cases, for example you can run sqlQuery in parallel, but practically I think it’s not very common thing and better to wrap to
async
in client code
w

withoutclass

12/13/2017, 2:37 PM
Totally, if building a library for blocking like network or DB calls I would avoid taking a stance on how it is consumed at all, let the client decide.