Last active
September 7, 2020 14:46
-
-
Save GrishinSergey/bb7cbd331848edf69e4af5f30bff73e8 to your computer and use it in GitHub Desktop.
ApiUtils.kt
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
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>> | |
} |
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
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] ?: "")) | |
} | |
} | |
} |
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
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