使用 RxJava 进行 Retrofit2

首先,将相关的依赖项添加到 build.gradle 文件中。

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'
    ....
}

然后创建你想要接收的模型:

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

创建一个包含用于与远程服务器交换数据的方法的接口:

public interface ApiServerRequests {

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

然后创建一个 Retrofit 实例:

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;
}

然后,从代码的任何地方,调用方法:

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
       }
   });