This tip is small but very useful if you are working with OKHTTP3 library. With the help of this code, you can cancel current or queue request of OkHTTP 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
OkHttpClient client = new OkHttpClient(); MediaType MEDIA_TYPE = MediaType.parse("application/json"); JSONObject postData = new JSONObject(); try { postData.put("q", "My Query"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString()); Request request = new Request.Builder() .url(Urls.search) .post(body) .header("Accept", "application/json") .header("Content-Type", "application/json") .tag("preRequest") .build(); // Cancel queue request for (Call call : client.dispatcher().queuedCalls()) { if (call.request().tag().equals("requestKey")) call.cancel(); } // Cancel last request for (Call call : client.dispatcher().runningCalls()) { if (call.request().tag().equals("preRequest")) { Log.e("cancle", "requestCancel"); call.cancel(); } } client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String mMessage = e.getMessage().toString(); Log.w("failure Response", mMessage); call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { final String mMessage = response.body().string(); Search.this.runOnUiThread(new Runnable() { @Override public void run() { try { /** Your response **/ } catch (JSONException e) { e.printStackTrace(); } } }); } }); |
Hope this small piece of code help you.