我有一个非常简单的用例:我需要针对一个端点发出一系列API请求,接受响应,做一些简单的转换,然后将所有的响应写到同一个文件中。
API请求是通过Kotlin的async特性发出的。但是当我尝试将它写到磁盘时,IDE正确地给了我一点提示,表明这是一个inappropriate blocking call。下面是一个玩具例子。
通过async发出这些请求并写入同一个文件的惯用方法是什么?
fun doAThing() {
val file = File("...")
file.writer().use{
for (x in 1..4) {
val response = async { makeHttpRequest(/*...*/) }
it.write(transform(response)) // This is, obviously, the blocking call.
}
}
}这个特定的片段是从协同机制上下文中执行的。
发布于 2020-03-17 23:29:13
这些异步调用可以并行执行,然后可以同时处理所有结果,这样您就可以知道写操作都是在同一个线程上完成的,甚至不需要一个线程上下文。这是因为所有的写操作都是在一行中完成的,中间没有任何挂起函数调用。
suspend fun doAThing() {
val responses = (1..4).map { index ->
async { makeHttpRequest(/*...*/) }
}.awaitAll()
val file = File("...")
withContext(Dispatchers.IO) {
file.writer().use{
for (response in responses) {
it.write(transform(response))
}
}
}
}发布于 2020-03-17 22:57:42
您需要打开并写入工作线程上的文件。这个怎么样:
suspend fun doAThing() = withContext(Dispatchers.IO) {
val file = File("...")
file.writer().use{
for (x in 1..4) {
val response = async { makeHttpRequest(...) }
it.write(transform(response)) // This is, obviously, the blocking call.
}
}
}https://stackoverflow.com/questions/60731117
复制相似问题