Skip to content

Instantly share code, notes, and snippets.

@VibeMage
Created March 3, 2020 07:23
Show Gist options
  • Select an option

  • Save VibeMage/0a73e2b7f5d767ea027ddb036dd2ca7f to your computer and use it in GitHub Desktop.

Select an option

Save VibeMage/0a73e2b7f5d767ea027ddb036dd2ca7f to your computer and use it in GitHub Desktop.
[Retrofit Call to Observable]#Android
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