1

根据Kotlin Extensions - async/await test,要使用异步 Web 请求,我应该将调用封装在协程中,如下面的示例,取自测试:

private fun myGetAsync(url: String) = GlobalScope.async {
    try {
        Ion.with(App.instance.applicationContext)
                .load(url)
                .asString()
                .await()
    }
    catch (e: Exception) {
        Log.e(TAG,"Fail",e)
    }
}

问题是当我尝试调用协程时,如下所示:

runBlocking {     // but this expression blocks the main thread
            Log.d(TAG,"RESULT" + myGetAsync("https://somewhere.earth/notExists").await())
        }

我收到以下库错误:

java.lang.NoSuchMethodError: No interface method setCallback(Lcom/koushikdutta/async/future/FutureCallback;)Lcom/koushikdutta/async/future/Future; in class Lcom/koushikdutta/async/future/Future; or its super classes (declaration of 'com.koushikdutta.async.future.Future' appears in /data/app/com.byte_artisan.mchat2.qua-Rd32X2D4BZg92hn423sVxA==/base.apk!classes4.dex)
        at com.koushikdutta.ion.IonRequestBuilder.resolveAndLoadRequest(IonRequestBuilder.java:383)
        at com.koushikdutta.ion.IonRequestBuilder.getLoaderEmitter(IonRequestBuilder.java:347)
        at com.koushikdutta.ion.IonRequestBuilder.getLoaderEmitter(IonRequestBuilder.java:310)
        at com.koushikdutta.ion.IonRequestBuilder.execute(IonRequestBuilder.java:675)
        at com.koushikdutta.ion.IonRequestBuilder.execute(IonRequestBuilder.java:636)
        at com.koushikdutta.ion.IonRequestBuilder.asString(IonRequestBuilder.java:701)
        at com.byte_artisan.mchat2.App$myGetAsync$1.invokeSuspend(App.kt:43)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)

我应该如何使用它?

4

1 回答 1

3

我使用的是旧版本的 com.koushikdutta.ion,与 androidasync-kotlin 库扩展不兼容。我通过将离子库设置为这些版本来修复:

implementation 'com.koushikdutta.ion:ion:3.0.8' 
implementation 'com.koushikdutta.async:androidasync-kotlin:3.0.9'
于 2019-11-03T00:33:10.620 回答