领域 Android:异步事务影响 UI 线程
Realm Android: Async Transaction affect UI thread
我目前正在使用领域来查询 RealmObjects 以在 GoogleMap 上显示它们。我正在执行读取并获取 RealmResults,但我找不到从 UI 线程将标记放在地图上的方法。我更喜欢使用异步调用来执行此操作,因为它会导致 UI 线程延迟约 150 毫秒。
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 是线程限制的
您可以尝试使用 RealmChangeListener
。 Realm 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));
}
}
}
上面的代码基本上是对 Realm 数据库进行异步查询,addChangeListener
注册了一个回调方法,在查询完成时调用,并将在以后的查询调用中调用(参考realm docs 了解更多信息)。
所以,我建议 运行 在 onStart
或 onResume
方法中使用上面的代码,并且不要忘记删除 onStop
或 onPause
方法,像这样:
locations.removeChangeListeners();
最后,别忘了关闭领域。希望能帮助到你!如有不明之处,请随时提问。
我目前正在使用领域来查询 RealmObjects 以在 GoogleMap 上显示它们。我正在执行读取并获取 RealmResults,但我找不到从 UI 线程将标记放在地图上的方法。我更喜欢使用异步调用来执行此操作,因为它会导致 UI 线程延迟约 150 毫秒。
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 是线程限制的
您可以尝试使用 RealmChangeListener
。 Realm 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));
}
}
}
上面的代码基本上是对 Realm 数据库进行异步查询,addChangeListener
注册了一个回调方法,在查询完成时调用,并将在以后的查询调用中调用(参考realm docs 了解更多信息)。
所以,我建议 运行 在 onStart
或 onResume
方法中使用上面的代码,并且不要忘记删除 onStop
或 onPause
方法,像这样:
locations.removeChangeListeners();
最后,别忘了关闭领域。希望能帮助到你!如有不明之处,请随时提问。