Last active
June 19, 2019 19:09
-
-
Save izackp/52e63814157a22f9135a97ec01c4a7bb to your computer and use it in GitHub Desktop.
(Code Saved For Later) Callback interface for android api requests without livedata. Not plugnplay but that shouldn't be a problem. It could probably be done with one less class...
This file contains 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
package any | |
import android.util.Log | |
import any.model.AppException | |
import any.model.NetworkState | |
import any.LiveModelCallback2 | |
import retrofit2.Call | |
import retrofit2.Callback | |
import retrofit2.Response | |
class APIRequest<T>( | |
val request: Call<T>, | |
var onSuccess:((result: T) -> Unit)? = null, | |
var onError:((acc: NetworkState) -> Unit)? = null | |
) { | |
var canceled = false | |
init { | |
request.enqueue(object: SimplifiedCallback<T>() { | |
override fun onSuccess(body: T) { | |
super.onSuccess(body) | |
if (canceled) { | |
return | |
} | |
onSuccess?.invoke(body) | |
} | |
override fun handleException(exception: AppException, code: Int?, errorData: String?) { | |
super.handleException(exception, code, errorData) | |
if (canceled) { | |
return | |
} | |
val error = NetworkState.error(exception.message, code ?: LiveModelCallback2.CODE_UNKNOWN, errorData) | |
onError?.invoke(error) | |
} | |
}) | |
} | |
} | |
open class SimplifiedCallback<T> : Callback<T> { | |
init { | |
} | |
override fun onResponse(call: Call<T>?, response: Response<T>?) { | |
val body = response?.body() | |
if (response?.isSuccessful == true && body != null ) { | |
onSuccess(body) | |
} else { | |
val exception = AppException("Request failed: ${response?.code()} ${response?.message()}") | |
handleException(exception, response?.code(), response?.errorBody()?.string()) | |
} | |
} | |
open fun onSuccess(body: T) { | |
} | |
override fun onFailure(call: Call<T>?, t: Throwable?) { | |
val exception = AppException(t) | |
handleException(exception) | |
} | |
open fun handleException(exception: AppException, code: Int? = null, errorData: String? = null) { | |
Log.e(BuildConfig.TAG, exception.message, exception) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment