我有一个使用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 更新到了 2.6.0。在 https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter 中写道它现在已过时。而在 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
据我所理解,我可以使用CallAdapter.Factory()
代替CoroutineCallAdapterFactory()
,但是它是抽象的。
如果在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.