Cancel current or queue request in OKHTTP3

people

Aneh Thakur

. 0 min read

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.

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.


More Stories from

Aneh Thakur
Aneh Thakur.3 min read

Get Started with TypeScript: A Beginner's Guide with Code Samples

TypeScript is a popular, powerful programming language that is a superset of JavaScript. If you're new to TypeScript, this beginner's guide is the perfect place to start. With clear explanations and code samples, you'll learn the basics of TypeScript and

.
Get Started with TypeScript: A Beginner's Guide with Code Samples
Aneh Thakur
Aneh Thakur.2 min read

TypeScript vs TSX: Understanding the Differences

This article delves into the key differences between TypeScript and TSX, two programming languages used for developing complex web applications. From syntax and static typing to React integration and code organization, learn which language is best suited

.
TypeScript vs TSX: Understanding the Differences
Aneh Thakur
Aneh Thakur.2 min read

Learn about the different types of React hooks with code examples

React hooks are a powerful feature that allow you to use state and other React features inside functional components. In this tutorial, you will learn about the different types of hooks available in React, and see code examples of how to use them in your

.
Learn about the different types of React hooks with code examples
Aneh Thakur
Aneh Thakur.2 min read

A step-by-step guide to deploying a ReactJS app online

Learn how to deploy your ReactJS app to the internet with this comprehensive tutorial. From setting up a hosting platform to building and uploading your code, we'll cover all the steps you need to take to get your app live. Whether you're a beginner or an

.
A step-by-step guide to deploying a ReactJS app online
Aneh Thakur
Aneh Thakur.3 min read

What is React context API?

React Context is a way to share values that are considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. It allows you to avoid prop drilling, or the passing of props through multiple levels

.
What is React context API?
Built on Koows