Skip to content

Instantly share code, notes, and snippets.

@finnkvan
Created January 12, 2019 11:17
Show Gist options
  • Save finnkvan/f5de992ad1fa06267c3c32f11213bd1c to your computer and use it in GitHub Desktop.
Save finnkvan/f5de992ad1fa06267c3c32f11213bd1c to your computer and use it in GitHub Desktop.
class LiveDataCallAdapter<R>(private val responseType: Type): CallAdapter<R, LiveData<ApiResponse<R>>> {
override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> {
return object : LiveData<ApiResponse<R>>() {
private var isSuccess = false
override fun onActive() {
super.onActive()
if (!isSuccess) enqueue()
}
override fun onInactive() {
super.onInactive()
dequeue()
}
private fun dequeue() {
if (call.isExecuted) call.cancel()
}
private fun enqueue() {
call.enqueue(object : Callback<R> {
override fun onFailure(call: Call<R>, t: Throwable) {
postValue(ApiResponse.create(UNKNOWN_CODE, t))
}
override fun onResponse(call: Call<R>, response: Response<R>) {
postValue(ApiResponse.create(response))
isSuccess = true
}
})
}
}
}
override fun responseType(): Type = responseType
}
@Shashank-CP
Copy link

Line #17
Shouldn't it be if (!call.isExecuted) call.cancel() ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment