5

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

4

2 回答 2

7

以下是使用协程的方法:

launch {
    val contents = withContext(Dispatchers.IO) {
        FileInputStream("filename.txt").use { it.readBytes() }
    }
    processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
于 2018-05-22T13:25:35.677 回答
1

从协程示例中查看此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 的一部分。

于 2021-12-13T20:05:37.220 回答