【发布时间】:2019-12-06 19:24:52
【问题描述】:
我需要做下一个:
- 检查是否存在配置文件
- 如果存在,则通过 Retrofit lib 启动异步 http 请求 (
getAdvertising()) - 如果不存在,则首先从远程加载配置文件(通过 Retrofit),如果成功获取结果,则启动异步 http 请求 (
getAdvertising())
我通过这样的回调来做到这一点:
fun getAdvertising(callback: Callback<List<Advertising>>) {
val call = myRestClient.advertising
executeAsync(call, callback)
}
private fun <T> executeAsync(call: Call<T>, callback: Callback<T>) {
val currentApplicationProfileResponse = foService.applicationProfileResponse
if (currentApplicationProfileResponse == null) {
getApplicationProfile(object : DefaultRestClientCallback<ApplicationProfileResponse>() {
override fun onTransportResponse(transportResponse: TransportResponse) {
super.onTransportResponse(transportResponse)
if (transportResponse.isSuccessful) {
//asynchronously
call.enqueue(callback)
} else { // not success
if (callback is DefaultRestClientCallback<*>) {
callback.onTransportResponse(transportResponse)
} else {
callback.onResponse(call, transportResponse.originalResponse as Response<T>?)
}
}
}
})
} else { // appProfile is not null
//asynchronously
call.enqueue(callback)
}
}
很好,工作正常。
但是代码太多了。是否可以用 Kotlin 的协程替换 Callback?
【问题讨论】:
-
Retrofit 现在支持协程:proandroiddev.com/…
-
你应该使用 Retrofit 2.6.0 它现在支持协程或者你可以这样做stackoverflow.com/questions/48552925/…
标签: android retrofit2 kotlin-coroutines