https://kotlinlang.org logo
#announcements
Title
# announcements
k

kevindmoore

07/16/2019, 5:01 AM
Coroutines
a

Andrew Gazelka

07/16/2019, 5:06 AM
but what are implementations of blocking File IO which should be run in a coroutine?
i.e., suspending functions which allow for File I/O
k

kevindmoore

07/16/2019, 5:51 AM
Not sure if I understand what you are asking, but if you use the Dispatchers.IO context that should work for you
k

kralli

07/16/2019, 6:05 AM
You take the blocking IO stuff like read the contents of a file and execute inside of the Dispatchers.IO context using
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
. And then you just program your asynchronous code like you would with coroutines.
Copy code
launch {
    val text = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someFile.readText() }

    println(text)
}
p

Paulius Ruminas

07/16/2019, 6:23 AM
https://github.com/Kotlin/coroutines-examples/blob/master/examples/sequence/sequenceOfLines.kt This is an example of reading lines with suspending functions. Basically you read a line and yield to let other coroutines do their job instead of reading everything in one go.
👍 1
3 Views