Created
January 12, 2019 11:17
-
-
Save finnkvan/f5de992ad1fa06267c3c32f11213bd1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line #17
Shouldn't it be
if (!call.isExecuted) call.cancel()
?