0

我目前使用realm查詢RealmObjects以在GoogleMap上顯示它們。我正在執行讀取並獲取RealmResults,但我無法找到從UI線程將標記放在地圖上的方法。我更喜歡用異步調用來做到這一點,因爲它會在UI線程上產生〜150ms的延遲。Realm Android:Async Transaction影響UI線程

public void loadLocations(final GoogleMap googleMap) { 
     try { 

     realm.executeTransactionAsync(new Realm.Transaction() { 

      @Override 
      public void execute(Realm realm) { 
       RealmResults<LocationObject> locations = realm.where(LocationObject.class).findAll(); 
       for (LocationObject location: locations) { 
         googleMap.addMarker(new MarkerOptions() 
           .position(new LatLng(location.lat, location.long)) 
       } 
      } 
     }); 
} 

如何在以後訪問UI線程上的RealmResults? Realm提到RealmObjects受線程限制

回答

3

您可以嘗試使用RealmChangeListenerRealm docs使用小狗的例子非常清楚地說明了這一點。

RealmResults<LocationObject> locations; 

//... 
    locations = realm.where(LocationObject.class).findAllAsync(); 

    locations.addChangeListener(new RealmChangeListener<Person>() { 
     @Override 
     public void onChange(RealmResults<LocationObject> locations) { 
      googleMap.clear(); 
      for (LocationObject location: locations) { 
       googleMap.addMarker(new MarkerOptions() 
          .position(new LatLng(location.lat, location.long)); 
      } 
     } 
    } 

上面的代碼基本上是做一個查詢異步的境界數據庫和addChangeListener註冊一個回調方法,當查詢完成後,將在未來的查詢調用來調用呼叫,以及(請參閱realm docs爲更多信息)。

因此,我建議在onStartonResume方法運行上面的代碼,不要忘了刪除更改監聽器onStop或方法,像這樣:

locations.removeChangeListeners(); 

最後,不要忘記關閉境界。希望能幫助到你!不要猶豫,詢問有沒有不清楚的地方。

+1

Ohhhhh所以當初始的「findAllAsync」事務完成時以及之後的每次更新都會調用更改偵聽器。很好的建議,謝謝@andyaldoo –

+0

@JesusGarcia確實如此。 –