Retrofit2 with RxJava

suggest change

First, add relevant dependencies into the build.gradle file.

dependencies {
    ....
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    ....
}

Then create the model you would like to receive:

public class Server {
    public String name;
    public String url;
    public String apikey;
    public List<Site> siteList;
}

Create an interface containing methods used to exchange data with remote server:

public interface ApiServerRequests {

    @GET("api/get-servers")
    public Observable<List<Server>> getServers();
}

Then create a Retrofit instance:

public ApiRequests DeviceAPIHelper ()
{
    Gson gson = new GsonBuilder().create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://example.com/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    api = retrofit.create(ApiServerRequests.class);
    return api;
}

Then, anywhere from the code, call the method:

apiRequests.getServers()
   .subscribeOn(Schedulers.io()) // the observable is emitted on io thread
   .observerOn(AndroidSchedulers.mainThread()) // Methods needed to handle request in background thread
   .subscribe(new Subscriber<List<Server>>() {
       @Override
       public void onCompleted() {
                    
       }

       @Override
       public void onError(Throwable e) {

       }

       @Override
       public void onNext(List<Server> servers) {
           //A list of servers is fetched successfully
       }
   });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents