efeyc efeyc - 1 month ago 7
Android Question

while calling more than one async requests with OkHttp, sometimes callbacks are interfered

I have two methods on CustomerService class, and when I call them on HomeFragment, one of the five times, I see that in getTransactions callback I get getCard service response

public class CustomerService {

OkHttpClient okHttpClient = new OkHttpClient();

.....

public void getTransactions(String memberId, Callback callback)
{
List<Pair> params = new ArrayList<>();
params.add(new Pair<>("member_id", memberId));

String url = BASE_URL + "customer/gettransaction/?" + getQuery(params);
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(callback);
}

public void getCard(String memberId, Callback callback)
{
List<Pair> params = new ArrayList<>();
params.add(new Pair<>("member_id", memberId));

String url = BASE_URL + "customer/getcard/?" + getQuery(params);
Request request = new Request.Builder().url(url).build();

okHttpClient.newCall(request).enqueue(callback);
}

}


And in the fragment class I call them as below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

rootView = inflater.inflate(R.layout.fragment_activities, container, false);
realm = Realm.getDefaultInstance();

getCardData();
getTransactions();

....

return rootView;
}

private void getTransactions() {
final User currentUser = UserRepository.getUser(realm);

customerService.getTransactions(currentUser.getMember_id(), new Callback() {
@Override
public void onFailure(Call call, final IOException e) {

Log.d(TAG, "Transaction service error: " + e.getMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {

Type responseType = new TypeToken<WsResponse<List<WsTransaction>>>() {}.getType();
final List<WsTransaction> wsTransactionList = LoyaltyService.getWsResponseData(response, responseType);

if (wsTransactionList != null) {

....
}
}
});
}

private void getCardData() {
final User currentUser = UserRepository.getUser(realm);

customerService.getCard(currentUser.getMember_id(), new Callback() {
@Override
public void onFailure(Call call, final IOException e) {

Log.d(TAG, "Customer - GetCard service error: " + e.getMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {

Type responseType = new TypeToken<WsResponse<WsCard>>() {}.getType();
final WsCard wsCard = LoyaltyService.getWsResponseData(response, responseType);
if (wsCard != null) {

.....
}
}
});
}


If I delay calling getTransactions for half second, then it has no problem. Or when I debug, I don't have any problem. Can somebody help me to understand what I'm missing?

Answer

It turned out to be a server side problem.