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