title: Implementing a AsyncTask with Realm
body: <p>I'm migrating an app to Realm and I have an AsyncTask like this (simplified for brevity) that I used to search through a list of objects and filter it based on a search query:</p>
  
  <pre><code>private class SearchTask extends AsyncTask&lt;String, Void&gt; {
  
  Realm realm;
  
  @Override
  protected List&lt;SearchResults&gt; doInBackground(String... params) {
  
      String searchString = params[0];
      realm = Realm.getDefaultInstance();
      ArrayList&lt;SearchResults&gt; myFoos = FooHelper.getAllFoo(realm);
      ArrayList&lt;Foo&gt; matches = new ArrayList&lt;&gt;();
  
      for (Foo aFoo : myFoos){
        if(!aFoo.getProperty().isEmpty()){
          matches.add(aFoo);
        }
      }
  
      realm.close();
      return matches;
  }
  
  @Override
  protected void onPostExecute(List&lt;SearchResults&gt; results) {
      super.onPostExecute(results);
  
      synchronized (SearchActivity.this){
        //use search results
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The problem is that when the results are returned they can't be accessed since they were created on another thread. The only solution I can think of is to return an array of primary keys from the async task then re-query for those again.</p>
  
  <p>There has to be a better way of basically doing SEARCH on a realm. Any suggestions?</p>