以下是使用协程进行操作的方法:
launch {
val contents = withContext(Dispatchers.IO) {
FileInputStream("filename.txt").use { it.readBytes() }
}
processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
Run Code Online (Sandbox Code Playgroud)
Java NIO 异步通道就是您想要的工具。从协程示例中查看此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)
}
})
}
Run Code Online (Sandbox Code Playgroud)
你只需打开一个然后在协程中AsynchronousFileChannel调用它,aRead()
val channel = AsynchronousFileChannel.open(Paths.get(fileName))
try {
val buf = ByteBuffer.allocate(4096)
val bytesRead = channel.aRead(buf)
} finally {
channel.close()
}
Run Code Online (Sandbox Code Playgroud)
这是一个必不可少的功能,不知道为什么它不是 coroutine-core lib 的一部分。
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |