Real-time search using AsyncTask?

I am writing an application that is looking for a database in real time. that is, when the user clicks the letters, he updates the list of search results.

Since the search may take some time, I need to do a background search and allow new keystrokes to restart the search. Thus, the user presses “a” (and the code starts searching “a”), then presses “b” - the code DO NOT wait until the search ends “a”, and then starts searching “ab”, Stop the search “a” and start a new search "ab".

  • To do this, I decided to search in AsyncTask. Is this a wise decision?

Now - whenever a keystroke is detected, I check to see if I have AsyncTask working. If I do this - I am signaling this (using a boolean value in AsyncTask), it should stop. Then set the timer to re-check AsyncTask for 10 ms to check if it is complete and start a new search.

  • Is this a smart method? Or is there another approach you would take?

TIA

+3
source share
1 answer

, AsyncTask - . , , - , - . asyncTask . , , , . , , asyncTask . - :

public void onClick() {
   if( searchTask != null ) {
      searchTask.cancel();
   }

   searchTask = new SearchTask( MyActivity.this ).execute( textInput.getText() );
}

public class SearchTask extends AsyncTask<String,Integer,List<SearchResult>> {
    private boolean canceled = false;

    protected onPostExecute( List<SearchResult> results ) {
       if( !canceled ) {
          activity.handleResults( results );
       }
    }

    public void cancel() {
       canceled = true;
    }
}

, onPostExecute() . cancel() , . , . GC. AsyncTask, . AsyncTask , , , , onPostExecute(). .

. , , , . , (, 10-50 max), , , (, 3). - , 3 . , .

+2

Source: https://habr.com/ru/post/1777785/


All Articles