user3473590
user3473590

Reputation:

Receiving custom parameter in retrofit callback

This is my post :

@POST("/path")
@FormUrlEncoded
void postIt(@Field("id") String id , Callback<Response> response);

and this is the Callback:

 private Callback<Response> responseCallBack = new Callback<Response>() {
    @Override
    public void success(Response response, Response response2) {
        // get the id 
    }

    @Override
    public void failure(RetrofitError error) {
        // do some thing
    }
};

Question:

in the callback i want to receive the id which posted in @POST, how should i do that?

and i can't change the server API

Upvotes: 3

Views: 2371

Answers (2)

user3473590
user3473590

Reputation:

to do this we need an abstract class

abstract class CallBackWithArgument<T> implements Callback<T> {
    String arg;

    CallBackWithArgument(String arg) {
        this.arg = arg;
    }

    CallBackWithArgument() {
    }

and make an instance

new CallBackWithArgument<Response>(id) {
        @Override
        public void success(Response response, Response response2) {
            //do something

        }

        @Override
        public void failure(RetrofitError error) {
            //do something

        }

    }

Upvotes: 3

Sergey Mashkov
Sergey Mashkov

Reputation: 4780

It's easy. You can simply make Callback to hold requested id and create new callback every time

class MyCallback extends Callback<Response> {
    private final String id;
    MyCallback(String id) {
        this.id = id
    }

    @Override
    public void success(Response response, Response response2) {
        // get the id 
    }

    @Override
    public void failure(RetrofitError error) {
        // do some thing
    }
}

So when you call service

myService.postIt("777", new MyCallback("777"))

Upvotes: 0

Related Questions