我想对我的Retrofit请求执行异步等待。
@GET("{companyId}/{filename}")
@Streaming
suspend fun getFilePart(
@Path(value = "companyId") companyId: Int,
@Path(value = "filename") filename: String,
@QueryMap queryMap: Map<String, String>
): Deferred<ResponseBody>
当我从CoroutineScope调用它时
val deferredList = pendingFiles.map {
async(Dispatchers.IO) {
try {
// runs in parallel in background thread
// Consider i have the data parameters....
apiManager.mApiService(base).getFilePart(it.companyId, fileName, urlQueryMap)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
因此,请求返回200,这意味着它是成功的,并且我看到了Logging with the File部分的数据。
W/System.err: java.lang.RuntimeException: Unable to invoke no-args constructor for com.google.firebase.inject.Deferred<okhttp3.ResponseBody>. Registering an InstanceCreator with Gson for this type may fix this problem.
W/System.err: at com.google.gson.internal.ConstructorConstructor$14.construct(ConstructorConstructor.java:228)
W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:212)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
W/System.err: at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
W/System.err: at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
W/System.err: at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:520)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:920)
W/System.err: Caused by: java.lang.UnsupportedOperationException: Interface can't be instantiated! Interface name: com.google.firebase.inject.Deferred
W/System.err: at com.google.gson.internal.UnsafeAllocator.assertInstantiable(UnsafeAllocator.java:117)
W/System.err: at com.google.gson.internal.UnsafeAllocator$1.newInstance(UnsafeAllocator.java:49)
W/System.err: at com.google.gson.internal.ConstructorConstructor$14.construct(ConstructorConstructor.java:225)
W/System.err: ... 9 more
1条答案
按热度按时间dkqlctbz1#
如果你的函数是
suspend
,它不应该返回Deferred
。只需这样声明它:带有
suspend
关键字的函数被当作常规函数使用(这就是协程的美妙之处),所以它们返回一个常规类型。当你使用协程构建器时,你实际上启动了异步代码,就像你使用async
时一样--这是一个返回Deferred<T>
并且不挂起的代码。