Advertisement
Guest User

Untitled

a guest
May 25th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.24 KB | None | 0 0
  1. package com.remek.rosettapos.communication.api
  2.  
  3. import retrofit2.Call
  4. import retrofit2.Callback
  5. import retrofit2.Response
  6.  
  7. /**
  8.  * Callback for the API calls.
  9.  */
  10. interface ApiCallback<T> : Callback<T> {
  11.  
  12.     companion object {
  13.         const val UNKNOWN_ERROR_MESSAGE = "Unknown error"
  14.     }
  15.  
  16.     override fun onResponse(call: Call<T>, response: Response<T>) {
  17.         val responseBody = response.body()
  18.         val error = response.errorBody()?.toString()
  19.         if (response.isSuccessful && responseBody != null) {
  20.             onSuccess(responseBody)
  21.         } else {
  22.             when (response.code()) {
  23.                 401 -> onError(CommunicationException.NotAuthenticatedException("Authentication not successful."))
  24.                 else -> onError(CommunicationException.UnknownCommunicationException(error ?: UNKNOWN_ERROR_MESSAGE))
  25.             }
  26.         }
  27.     }
  28.  
  29.     override fun onFailure(call: Call<T>, t: Throwable) {
  30.         onError(CommunicationException.UnknownCommunicationException(UNKNOWN_ERROR_MESSAGE))
  31.     }
  32.  
  33.     /**
  34.      * Called after a successful network request.
  35.      *
  36.      * @param response the response object.
  37.      */
  38.     fun onSuccess(response: T)
  39.  
  40.     /**
  41.      * Called if network communication fails.
  42.      *
  43.      * @param error an exception that may tell more about the error.
  44.      */
  45.     fun onError(error: CommunicationException)
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement