我有一个使用 Kotlin 协程和 Retrofit 的项目。
我有这些依赖项:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
今天我更新了Retrofit to 2.6.0在项目中。在https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter据报道,它现在已被弃用。在https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05 https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05据说Retrofit目前支持suspend
.
所以,我删除了retrofit2-kotlin-coroutines-adapter:0.9.2
并在 Retrofit 客户端中更改了这些行:
retrofit = Retrofit.Builder()
.baseUrl(SERVER_URL)
.client(okHttpClient)
.addConverterFactory(MyGsonFactory.create(gson))
//.addCallAdapterFactory(CoroutineCallAdapterFactory()) - removed it.
.build()
运行时,第一个请求捕获异常:
java.lang.IllegalArgumentException: Unable to create call adapter for kotlinx.coroutines.Deferred<com.package.model.response.UserInfoResponse>
for method Api.getUserInfo
据我了解,而不是CoroutineCallAdapterFactory()
我可以用CallAdapter.Factory()
,但它是抽象的。
如果在 Api 类中我更改了请求添加suspend
在一开始的时候:
@FormUrlEncoded
@POST("user/info/")
suspend fun getUserInfo(@Field("token") token: String): Deferred<UserInfoResponse>
override suspend fun getUserInfo(token: String): Deferred<UserInfoResponse> =
service.getUserInfo(token)
我得到这个异常:
java.lang.RuntimeException: Unable to invoke no-args constructor for kotlinx.coroutines.Deferred<com.package.model.response.UserInfoResponse>. Registering an InstanceCreator with Gson for this type may fix this problem.