Created
March 3, 2020 07:23
-
-
Save VibeMage/0a73e2b7f5d767ea027ddb036dd2ca7f to your computer and use it in GitHub Desktop.
[Retrofit Call to Observable]#Android
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
| public static <T extends ApiResponse> Observable<T> CallToObservable(Call<T> originalCall) { | |
| return Observable.<T>create(subscriber -> { | |
| Call<T> call = originalCall.clone(); | |
| CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber); | |
| subscriber.add(arbiter); | |
| subscriber.setProducer(arbiter); | |
| Response<T> response; | |
| try { | |
| response = call.execute(); | |
| if (!response.isSuccessful()) { | |
| throw new HttpException(response); | |
| } | |
| T body = response.body(); | |
| if (body != null) { | |
| if (!body.isSuccess()) { | |
| throw new ApiException(body.code, body.message); | |
| } | |
| arbiter.emitResponse(body); | |
| } else { | |
| throw new Exception("NullResponse"); | |
| } | |
| } catch (Exception e) { | |
| Exceptions.throwIfFatal(e); | |
| arbiter.emitError(e); | |
| } | |
| }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment