Search code examples
retrofit

How can I extend a Retrofit 2.0 Call?


I want to achieve something like this:

MyCall<MyResponse> call = service.login(loginRequest);

call.enqueue(
    new Runnable() {
        @Override
        public void run() {
            // onResponse
            }
        }, new Runnable() {
            @Override
            public void run() {
                // onFailure
            }
    });

so that when I have to make a call I don't need to parse the response in each callback and the code is a little lighter and reusable.

I tried the code from this snippet but I get the error:

Unable to create call adapter for XXXX.

What am I missing?


Solution

  • I did not extend Call but I extend Callback, it's also help to make the code is a little lighter and reusable.

    public abstract class CustomCallback<T> implements Callback<T> {
    
        @Override
        public void onResponse(final Response<T> response, Retrofit retrofit) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    onRequestSuccess(response);
                }
            };
            runnable.run();
        }
    
        @Override
        public void onFailure(final Throwable t) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    onRequestFail(t);
                }
            };
            runnable.run();
    
        }
    
        public abstract void onRequestSuccess(Response<T> response);
    
        public abstract void onRequestFail(Throwable t);
    
    }
    

    Then when you call enqueue():

    call.enqueue(new CustomCallback<YourObject>() {
                @Override
                public void onRequestSuccess(final Response<YourObject> response)
                {
                }
    
                @Override
                public void onRequestFail(final Throwable t) {
    
                }
            });
    

    Hope it helps