gpt4 book ai didi

java - 将 RealmObjectChangeListener 添加到异步下载的 RealmObject

转载 作者:行者123 更新时间:2023-12-02 02:15:14 25 4
gpt4 key购买 nike

假设异步API调用返回Member Data,它是一个RealmObject,并且Member被保存到realm中。

public class Member extends RealmObject { 
String name;
}

现在我想将 RealmObjectChangeListener 添加到成员对象(例如成员),以便我们可以在数据可用时更新 UI。但是,首先,Member 表为空,member 为 null,因为用于获取成员数据的 API 调用是异步的。将 RealmObjectChangeListener 添加到成员将导致 NullPointerException。遇到这种情况该如何处理呢?

最佳答案

如果您正在监听所有成员,那么很简单:保留对成员的字段引用(在 RecyclerView 的 ViewHolder 中很容易)并将 RealmObjectChangeListener 添加到从 results.get() 获取的成员中,绑定(bind)到 ViewHolder。

void bind(Member member) {
if(this.member != null) {
this.member.removeAllChangeListeners();
}
this.member = member;
this.member.addChangeListener(...);
<小时/>

假设您正在等待具有特定名称的特定成员,并且您只关心该成员:

private final Handler handler = new Handler(Looper.getMainLooper());

private RealmResults<Member> objectResults;
private RealmChangeListener<RealmResults<Member>> objectTracker = (results) -> {
if(member != null && member.isValid()) {
return;
}
if(realm.isInTransaction()) {
handler.post(() -> {
setupMember(results);
});
} else {
setupMember(results);
}
};

private void setupMember(RealmResults<Member> members) {
if(member != null && member.isValid()) {
member.removeAllChangeListeners();
}
member = members.first(null);
if(member != null) {
member.addChangeListener((member, fieldChangeSet) -> {
// do whatever
});
}
}

private Member member;

private Realm realm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
realm = Realm.getDefaultInstance();
objectResults = realm.where(Member.class).equalTo("name", name).findAllAsync();
objectResults.addChangeListener(objectTracker);
}

@Override
protected void onDestroy() {
super.onDestroy();
if(member != null) {
member.removeAllChangeListeners();
}
objectResults.removeAllChangeListeners();
realm.close();
}
<小时/>

编辑:如果您不需要字段级更改:

private RealmResults<Member> objectResults;
private RealmChangeListener<RealmResults<Member>> objectTracker = (results) -> {
setupMember(results);
};

private void setupMember(RealmResults<Member> members) {
Member member = members.first(null);
if(member != null) {
updateViews(member); // update views with member
} else {
// member doesn't exist or was deleted
}
}

private Realm realm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
realm = Realm.getDefaultInstance();
objectResults = realm.where(Member.class).equalTo("name", name).findAllAsync();
objectResults.addChangeListener(objectTracker);
}

@Override
protected void onDestroy() {
super.onDestroy();
objectResults.removeAllChangeListeners();
realm.close();
}

关于java - 将 RealmObjectChangeListener 添加到异步下载的 RealmObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49385023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com