Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How to read from file asynchronously?

Is there any kotlin idiomatic way to read a file content's asynchronously? I couldn't find anything in documentation.

like image 950
alisabzevari Avatar asked May 22 '18 13:05

alisabzevari


1 Answers

Here's how to do it with coroutines:

launch {
    val contents = withContext(Dispatchers.IO) {
        FileInputStream("filename.txt").use { it.readBytes() }
    }
    processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
like image 123
Marko Topolnik Avatar answered Nov 13 '22 00:11

Marko Topolnik