我有一个接口来生成具体的改装客户端类,像这样:
interface SyncService {
@GET("event/sampleValue")
fun currentEvent(): Call<CurrentEventResponse>
@GET("event")
fun getEvents(): Call<List<EventResponse>>
@POST("Answer")
fun sendAnswers(@Body requests: Array<AnswerRequest>): Call<SendAnswerResponse>
}
然后我需要将对viewmodel类中currentEvent()和getEvents()的调用排队:
class SettingsViewModel(
application: Application,
) : AndroidViewModel(application), Callback<List<EventResponse>> {
// ...
private fun getEvents() {
ApiClient.syncService().getEvents().enqueue(this)
}
fun getCurrentEventData() {
ApiClient.syncService().currentEvent().enqueue(this)
}
/**
* Failure event handler for the getEvents API request.
*/
override fun onFailure(call: Call<List<EventResponse>>, t: Throwable) {
LOGE(TAG, "getEvents API request failed.", t)
}
/**
* Response event handler for the getEvents API request.
*/
override fun onResponse(call: Call<List<EventResponse>>, response: Response<List<EventResponse>>) {
if (response.isSuccessful) {
response.body()?.let { events.addAll(it) }
}
}
}
问题是我做不到
SettingsViewModel
类实现两者
Callback<List<EventResponse>>
和
Callback<CurrentEventResponse>
因为它声称JVM签名是相同的。
一个选项是内联创建回调对象,如:
fun getCurrentEventData() {
ApiClient.syncService().currentEvent().enqueue(object : Callback<CurrentEventResponse> {
override fun onFailure(call: Call<CurrentEventResponse>, t: Throwable) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onResponse(call: Call<CurrentEventResponse>, response: Response<CurrentEventResponse>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
}
但是我想分离事件处理程序,所以调用方法(
getCurrentEventData()
)不符合
onResponse
和
onFailure
事件。
我还能做什么?