Skip to content

Instantly share code, notes, and snippets.

@kalpeshp0310
Last active April 14, 2017 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalpeshp0310/754aa7d80e3cbb56674c6f3dea7b4a20 to your computer and use it in GitHub Desktop.
Save kalpeshp0310/754aa7d80e3cbb56674c6f3dea7b4a20 to your computer and use it in GitHub Desktop.
Network Helper for RxJava, OkHttp, Gson
public class NetworkHelper {
private OkHttpClient okHttpClient;
private Gson gson;
public NetworkHelper(OkHttpClient okHttpClient, Gson gson) {
this.okHttpClient = okHttpClient;
this.gson = gson;
}
/**
makes a GET call through OkHttp
return an Observable of type defined by clazz
Usage:
NetworkHelper.get(baseUrl, String.class).compose(applySchedulers()).subscribe(s->{
Do Awesome Things Here
})
**/
public static <E> Observable<E> get(final String url, final Class<E> clazz) {
return Observable.fromCallable(() -> {
Request request = new Request.Builder().url(url).get().build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
String responseString = response.body().string();
return gson.fromJson(responseString, clazz);
} else {
throw constructUnknownResponseException(response);
}
});
}
static RuntimeException constructUnknownResponseException(Response response) throws IOException {
return new RuntimeException(String.format("Unknown response from Server {Code: %d Body: %s}", response.code(), response.body().string()));
}
<T> Observable.Transformer<T, T> applySchedulers() {
return observable -> observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment