Kotlin - 如何异步读取文件?

时间:2018-05-22 13:17:20

标签: kotlin kotlinx.coroutines

是否有任何kotlin习惯方式异步读取文件内容?我在文档中找不到任何内容。

1 个答案:

答案 0 :(得分:3)

以下是如何使用协同程序执行此操作:

launch {
    val contents = withContext(Dispatchers.IO) {
        FileInputStream("filename.txt").use { it.readBytes() }
    }
    processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()