user2934930
user2934930

Reputation: 1146

Add Response call back when using retrofit with rxjava

I am using retrofit with Rxjava to get response from API as you can see the method i am using i can't see what's coming in the response and offcourse i don't need to becuase i am providing GsonConverter to retrofit but for some debugging reason i need to see the response that coming from API. How can i do this, what code i need to add.

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

Upvotes: 0

Views: 616

Answers (2)

Brad
Brad

Reputation: 513

Daniel Lew's approach is quick and contains the least amount of boiler plate code. However, this may force you to refactor your networking logic. Since you mention needing this for debugging purposes, perhaps using a configured OkHttpClient with Interceptors is a less intrusive strategy.

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

Upvotes: 0

Dan Lew
Dan Lew

Reputation: 87440

You can only do this as of Retrofit 2: Change the return type to include Response:

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

You can also use Observable<Result<Product>> if you want to see all possible errors in onNext (including IOException, which normally uses onError).

Upvotes: 2

Related Questions