rx-java Retrofit and RxJava Set up Retrofit and RxJava


Example

Retrofit2 comes with support for multiple pluggable execution mechanisms, one of them is RxJava.

To use retrofit with RxJava you first need to add the Retrofit RxJava adapter to your project:

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

then you need to add the adapter when building your retrofit instance:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com")
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .build();

In your interface when you define the API the return type should be Observable eg:

public interface GitHubService {
  @GET("users/{user}/repos")
  Observable<List<Repo>> listRepos(@Path("user") String user);
}

You can also use Single instead of Observable.