Android:如何访问Ion库中的wait()方法
我正在使用Android的一个库。如中所示,可以使用名为Android:如何访问Ion库中的wait()方法,android,kotlin,ion,Android,Kotlin,Ion,我正在使用Android的一个库。如中所示,可以使用名为await()的方法,如下所示: fun getFiles(files: Array<String>) = async { for (file in files) { Ion.with(context) .load(file) .asString() .await() } } 这就引出了我的第一个问题,如何使用离子库中的.await()方法 我想也
await()
的方法,如下所示:
fun getFiles(files: Array<String>) = async {
for (file in files) {
Ion.with(context)
.load(file)
.asString()
.await()
}
}
这就引出了我的第一个问题,如何使用离子库中的.await()
方法
我想也许我必须手动下载,这是源文件夹中唯一的文件
因此,我下载了该文件并将其放入我的项目包中。我将下载文件顶部的包声明从package com.koushikdutta.ion.kotlin
更改为package com.example.vroy1.recylerviewtest
这似乎部分解决了问题,因为我不再在Android Studio中出现“未解决的引用:等待”错误
但是,AsyncWait.kt文件拒绝编译。我有几个错误
其中一个错误发生在文件顶部的导入语句中。错误是:
这就引出了我的第二个问题。如果使用
.await()
的唯一方法是手动下载AsyncAwait.kt,那么如何修复此错误以编译文件?我建议您定义一些类似这样的实用函数
suspend fun <T> customAsync(block: suspend CoroutineScope.() -> T): Deferred<T> {
val deferred: Deferred<T> = async(CommonPool) { block() }
return deferred
}
suspend fun <T> asyncAwait(block: suspend CoroutineScope.() -> T): T = customAsync(block).await()
这个答案在两个方面是错误的:1。它建议对已经异步的API使用async await。2.
async(block).await()不是async
的用途。请改用withContext(CommonPool)
。@Marko Topolnik我的答案不适用于getFiles()不异步的情况。它适用于getFiles()是一个普通函数的情况,我的回答中已经提到了这一点。如您所见,async(block).await()
正在调用上述函数,该函数已经具有val deferred:deferred=async(CommonPool){block()}
那么,您为什么要在这里写关于异步API的答案呢?此外,您说“如果您想在另一个线程中执行它”,但您的async(block:…)
已将块提交到另一个线程。@我的异步方法的Marko Topolnik命名看起来像是Coroutine的内部函数,因此现在我已更改了命名,这样就不会出现混淆。我没有被您的命名搞糊涂customAsync
将块提交到CommonPool
。该块在另一个线程上执行,无论您是否在之后调用await()
。
suspend fun <T> customAsync(block: suspend CoroutineScope.() -> T): Deferred<T> {
val deferred: Deferred<T> = async(CommonPool) { block() }
return deferred
}
suspend fun <T> asyncAwait(block: suspend CoroutineScope.() -> T): T = customAsync(block).await()
launch(UI) {
val result = asyncAwait {
getFiles(listOfStrings)
}
}