【发布时间】:2018-11-01 06:49:57
【问题描述】:
是否有任何 kotlin 惯用的方式来异步读取文件内容?我在文档中找不到任何内容。
【问题讨论】:
是否有任何 kotlin 惯用的方式来异步读取文件内容?我在文档中找不到任何内容。
【问题讨论】:
查看coroutine example 中的这个AsynchronousFileChannel.aRead 扩展函数:
suspend fun AsynchronousFileChannel.aRead(buf: ByteBuffer): Int =
suspendCoroutine { cont ->
read(buf, 0L, Unit, object : CompletionHandler<Int, Unit> {
override fun completed(bytesRead: Int, attachment: Unit) {
cont.resume(bytesRead)
}
override fun failed(exception: Throwable, attachment: Unit) {
cont.resumeWithException(exception)
}
})
}
非常基础,不知道为什么它不是 coroutine-core lib 的一部分。
【讨论】:
以下是使用协程的方法:
launch {
val contents = withContext(Dispatchers.IO) {
FileInputStream("filename.txt").use { it.readBytes() }
}
processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
【讨论】: