Skip to content

Instantly share code, notes, and snippets.

@GrishinSergey
Last active September 7, 2020 14:46
Show Gist options
  • Save GrishinSergey/bb7cbd331848edf69e4af5f30bff73e8 to your computer and use it in GitHub Desktop.
Save GrishinSergey/bb7cbd331848edf69e4af5f30bff73e8 to your computer and use it in GitHub Desktop.
ApiUtils.kt
import io.reactivex.Single
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("Controller/action")
fun apiCallName(
@Query("param") param: Long
): Single<Response<ApiResponseType>>
}
fun <T> Single<Response<T>>.getResponseOrError(): Single<T> {
return flatMap {
if (it.isSuccessful && (it.body() != null) && (it.errorBody() == null)) {
Single.create<T> { e -> e.onSuccess(it.body()!!) }
} else {
Single.create<T> { e -> e.onError(ApiRequestFailedException(it.headers()[REASON_MESSAGE_KEY] ?: "")) }
}
}
}
fun <T> Single<Response<T>>.getCompletableOrError(): Completable {
return flatMapCompletable {
if (it.isSuccessful && (it.errorBody() == null)) {
if (it.body() is Boolean) {
if (it.body() as Boolean) {
Completable.complete()
} else {
Completable.error(ApiRequestFailedException(it.headers()[REASON_MESSAGE_KEY] ?: ""))
}
} else {
Completable.complete()
}
} else {
Completable.error(ApiRequestFailedException(it.headers()[REASON_MESSAGE_KEY] ?: ""))
}
}
}
class Repository {
fun getData(): Single<ApiResponseType> {
return apiService.apiCallName().getResponseOrError()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment