Last active
September 5, 2017 10:14
-
-
Save arkty/7f62f54d7a82800ef2c1585607c49d62 to your computer and use it in GitHub Desktop.
Android Retrofit
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 ApiException(val error: ApiError) : Exception() { | |
override val message: String? | |
get() = error.messages.getOrNull(0) | |
// тут можно добавить метод getOrDefault(fallbackMessage: String) | |
companion object { | |
fun from(body: ResponseBody) = ApiException(ApiError.from(body)) | |
} | |
} | |
// Данные, которые пришли с сервера | |
data class ApiError( | |
val status: Int, | |
val messages: List<String>, | |
val type: String, | |
val stack: String | |
){ | |
companion object { | |
val gson = GsonBuilder().create()!! | |
fun from(body: ResponseBody) = gson.fromJson(body.string(), ApiError::class.java)!! | |
} | |
} | |
// Экстеншны в помощь | |
fun <T> Single<Response<T>>.asRetrofitResponse() = this | |
.map { | |
if (!it.isSuccessful) { | |
throw ApiException.from(it.errorBody()) | |
} | |
it | |
}!! | |
fun <T> Single<Response<T>>.asRetrofitBody() = this | |
.asRetrofitResponse() | |
.map { it.body() } | |
// Использование(пример) | |
fun login(username: String, password: String) = api | |
.authorizeUser(AuthorizeUserRequest(username, password)) | |
.asRetrofitResponse() | |
.map { | |
it.headers()[Headers.USER_TOKEN] | |
} | |
.doOnSuccess { token -> | |
accessToken.set(token) | |
} | |
// Че в ретрофите | |
@POST("login") | |
fun authorizeUser( | |
@Body request: AuthorizeUserRequest | |
): Single<Response<UserResponse>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment