use*_*657 6 android retrofit2 rx-java2
我的 API 客户端
public class ApiClient {
public static final String BASE_URL = "http://baseurl.com/wp-json/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Run Code Online (Sandbox Code Playgroud)
我的端点接口
public interface ApiInterface {
@GET("posts/category/politics/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getPoliticsArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
@GET("posts/category/economy/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getEconomyArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
@GET("posts/category/sports/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getSportsArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
}
Run Code Online (Sandbox Code Playgroud)
如何在不使用 lambda 函数的情况下使用 flatMap 依次调用 getPoliticsArrayListObservable 和 getEconomyArrayListObservable 和 getSportsArrayListObservable?
我试过这样的事情:
final ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Observable.just(apiInterface)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Function<ApiInterface, Observable<ArrayList<ModelNewsPaged>>>() {
@Override
public Observable<ArrayList<ModelNewsPaged>> apply(ApiInterface apiInterface) throws Exception {
return apiInterface.getPoliticsArrayListObservable(10,1);
}
})
.subscribe(new Observer<ArrayList<ModelNewsPaged>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
Log.d("flatMap", "onComplete");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Log.d("flatMap", "onError");
}
@Override
public void onNext(ArrayList<ModelNewsPaged> integer) {
Log.d("flatMap", "Final result: " + integer.toString());
}
});
Run Code Online (Sandbox Code Playgroud)
但这里的问题是,我无法链接更多的 flatMap 方法。任何帮助都感激不尽。
您可以使用 RxJava 的 Concat 运算符来顺序调用 API。如果您不关心顺序,可以使用 Zip。
好吧,我可能会这样做。如果您不与 API 保持开放连接,则应将 API 调用视为单一调用。
apiService.getDailyCounts()
.flatMap { apiService.updateCounts() }
.flatMap { apiService.changeTrialCourtCaseName() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |