我有一个模型成员扩展了RealmObject 。在我的活动中,我在其上设置了onAddChangeListener,如下所示:
private RealmChangeListener<RealmResults<Member>> memberTracker = this::setupProfileUI;
private Member member;
private void setupProfileUI(RealmResults<MemberDetails> results) {
member = results.first(null);
updateProfileUI();
}
在onCreate()中,我做
RealmResults<Member> memberResults = realm.where(Member.class).findAll();
memberResults.addChangeListener(memberTracker);
member = memberResults.first(null);
我根据选择的微调器
更新后台线程上的成员对象 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Request.updateMember(new Request.Callback<Member>() {
@Override
public void onResponse(Response<Member> response) {
Log.d(TAG, "updateMember: " + member.getLocation().getCity());
Log.d(TAG, "updateMember: " + response.body().getLocation().getCity());
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "onFailure: Member Update Failed");
}
});
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
onResponse回调中的第二个Log语句从API的响应打印成员的城市,同时首先从成员的当前值打印城市值。后面的值保持不变,Activity不接收更新通知。
通过调用辅助函数,在Request.updateMember()中更新成员,如下所示
private static void updateMemberDetails(Response<Member> response) {
if (response.isSuccessful()) {
try(Realm realmInstance = Realm.getDefaultInstance()) {
Member member = response.body();
if (member != null) {
realmInstance.executeTransaction(realm -> realm.insertOrUpdate(member));
}
}
}
}
我在成功的异步调用中手动检查了.realm文件,确认.realm文件中的成员确实已更新,但Activity中的成员对象没有更新,也没有任何更新通知。
答案 0 :(得分:1)
RealmResults<Member> memberResults = realm.where(Member.class).findAll();
根据@Size
的文档:
注册更改侦听器不会阻止底层RealmResults被垃圾回收。如果RealmResults被垃圾收集,则更改侦听器将停止被触发。为避免这种情况,请尽可能长时间保持强有力的参考,例如在一个类变量中。
public class MyActivity extends AppCompatActivity {
private RealmResults<Person> results; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
results = realm.where(Person.class).findAllAsync();
results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
@Override
public void onChange(RealmResults<Person> persons) {
// React to change
}
});
}
}
所以你应该这样做。