Search code examples
androidsearchretrofittextwatcher

Can i start a new Thread for every character entered in EditText for searching


Good Afternoon, I have a question please have look at this.

I am using Retrofit beta 2 for retrieving data from api. I have an EditText in which I want to search some names from server. I got the output also, but for example consider there are some names:

ABC,XYZ,PQR,STU,ETC. These are the names stored in the server and I am retrieving this names using Retrofit beta2.

When I searched for ABC or abc it will display the results and when I removed the string from the EditText then nothing is displayed.

Till here I Have done.

My question is when I type names fast then the result is something else.

So, can anyone tell me how to avoid this.

Thank You.


Solution

  • The Call object has a couple of utility methods you can use namely isExecuted and cancel to control your request.

    http://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html

    I am assuming you are using TextWatcher. Pseudo-code as follows:

    public void afterTextChanged (Editable s) {
        // Cancel the request first before sending it again; this way you won't have two separate calls
        if(call != null && call.isExecuted()) {
          call.cancel();
        }
    
        // reinitialize call and execute it again
    }
    

    Generally speaking, it is ill-advised to listen for immediate input from user to spawn an action: you should rethink your approach; it's better to put a "submit" or button to execute the API call; otherwise you'll be spamming the server with several HTTP requests per input.