Reputation: 10076
i am working with instagram API in that i have use ion lib for API request my question is how to handle multiple request's response using my code like this
public class UserProfileActivity extends AppCompatActivity implements
FutureCallback {
:
:
Ion.with(context)
.load("http://example.com/test1")
.asString()
.setCallback(this);
Ion.with(context)
.load("http://example.com/test2")
.asString()
.setCallback(this);
@Override
public void onCompleted(Exception exception, String response) {
}
}
//and i don't want to use like this (anonymous class )
Ion.with(context)
.load("http://example.com/thing.json")
.asJsonObject()
.setCallback(new FutureCallback() {
@Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
in this case if i am requesting 2 request test1 and test2 how can i differentiate 2 request response in one callback
and Same thing with Volley also
any help on multi treading in android ?
Upvotes: 0
Views: 761
Reputation: 1008
You can add a unique Id value for each of the request (the Key has to be the same) in the header and then in the response check for the same request ID. Note that you need to use ".withResponse()" and also implement "FutureCallback< Response>".
public class UserProfileActivity extends AppCompatActivity implements
FutureCallback<Response<String>> {
:
:
Ion.with(context)
.load("http://example.com/test1")
.setHeader("REQUEST_ID","test1")
.asString()
.withResponse()
.setCallback(this);
Ion.with(context)
.load("http://example.com/test2")
.setHeader("REQUEST_ID","test2")
.asString()
.withResponse()
.setCallback(this);
@Override
public void onCompleted(Exception exception, Response<String> response) {
if (response.getRequest().getHeaders().get("REQUEST_ID").equals("test1")) {
//do something based on response of test 1
}else if (response.getRequest().getHeaders().get("REQUEST_ID").equals("test2")) {
//do something based on response of test 2
}
}
}
In the above example, you can make "REQUEST_ID" as a constant.
Upvotes: 1
Reputation: 1246
You can pass Context of any Class, Fragment or Activity in
1- .setCallBack(context)
After doing so, implement the FutureCallBack in the class, Fragment or Activity you provided the context.
After implementing the FutureCallBack it will declare the method onComplete() where you will be getting your response.
Upvotes: 0