Last active
April 14, 2017 08:25
-
-
Save kalpeshp0310/754aa7d80e3cbb56674c6f3dea7b4a20 to your computer and use it in GitHub Desktop.
Network Helper for RxJava, OkHttp, Gson
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 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