为同一类中的多个服务方法实现Retrofit的Callback接口

时间:2018-09-21 13:39:12

标签: kotlin retrofit

我有一个界面来生成具体的Retrofit客户端类,如下所示:

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())不会随onResponseonFailure事件的逻辑而增长。

我还能做什么?

0 个答案:

没有答案