Skip to content

Instantly share code, notes, and snippets.

@miao1007
Created September 3, 2015 11:54
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save miao1007/7f75ccdf8b3026c077d6 to your computer and use it in GitHub Desktop.
Save miao1007/7f75ccdf8b3026c077d6 to your computer and use it in GitHub Desktop.
Retrofit 2.0 RxJava Sample
dependencies {
compile 'io.reactivex:rxjava:1.0.12'
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
}
/**
* Logging with Retrofit
* RxJava with Retrofit
*
*/
public class Sample {
public static void main(String[] args) throws Exception{
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
Retrofit retrofit = new Retrofit.Builder().baseUrl(IPService.END).client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
retrofit.create(IPService.class)
.getIPInfo("58.19.239.11").filter(jsonObject -> jsonObject.get("code").getAsInt()==0)
.map(jsonObject1 -> jsonObject1.get("data"))
.subscribe(System.out::println);
return;
}
interface IPService {
String END = "http://ip.taobao.com";
@GET("/service/getIpInfo.php") Observable<JsonObject> getIPInfo(@Query("ip") String ip);
}
static class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
System.out.println(
String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
System.out.println(
String.format("Received response for %s in %.1fms%n%s", response.request().url(),
(t2 - t1) / 1e6d, response.headers()));
return response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment