【问题标题】:Add Response call back when using retrofit with rxjava使用 rxjava 进行改造时添加响应回调
【发布时间】:2016-04-12 07:07:33
【问题描述】:

我正在使用 Rxjava 进行改造以从 API 获取响应,因为您可以看到我正在使用的方法我看不到响应中的内容,当然我不需要因为我提供 GsonConverter 进行改造,但是为了一些调试原因,我需要查看来自 API 的响应。我该怎么做,我需要添加什么代码。

public interface ProductApiService
{
    String END_POINT = "http://beta.site.com/index.php/restmob/";

    @GET(Url.URL_PRODUCT_API)
    Observable<Product> getProducts(@Query("some_id") String cid);

    class Creator
    {
        public static ProductApiService getProductAPIService() {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ProductApiService.END_POINT)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();

            return retrofit.create(ProductApiService.class);
        }
    }
}

【问题讨论】:

    标签: android retrofit rx-java


    【解决方案1】:

    您只能从 Retrofit 2 开始执行此操作:更改返回类型以包含 Response

    @GET(Url.URL_PRODUCT_API)
    Observable<Response<Product>> getProducts(/* ...etc... */);
    

    如果您想查看onNext(包括IOException,通常使用onError)中所有可能的错误,您也可以使用Observable&lt;Result&lt;Product&gt;&gt;

    【讨论】:

      【解决方案2】:

      Daniel Lew 的方法很快,并且包含最少的样板代码。但是,这可能会迫使您重构网络逻辑。由于您提到出于调试目的需要此功能,因此使用配置的 OkHttpClientInterceptors 可能是一种侵入性较小的策略。

      OkHttpClient httpClient = new OkHttpClient.Builder()
          .addInterceptor(new Interceptor() {
              @Override
              public Response intercept(Chain chain) throws IOException {
                  Request req = chain.request();
                  Response resp = chain.proceed(req);
                  // ... do something with response
                  return resp;
              }
          })
          .build();
      
      Retrofit retrofit = new Retrofit.Builder()
          .client(httpClient)
          .baseUrl(ProductApiService.END_POINT)
          .addConverterFactory(GsonConverterFactory.create(gson))
          .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
          .build();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-11
        • 2018-05-03
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        • 2018-05-03
        • 2019-08-01
        相关资源
        最近更新 更多