我正在使用一个使用Firebase作为数据存储库的应用程序。我只是重构了整个应用程序,以实现干净的架构和RxJava。这样做时,我发现管理我的模型对象有问题。
我的问题是:我有一个职位。使用我可以从Firebase数据库引用检索的相同字段和值初始化:
public Post(Author author, String full_url, String full_storage_uri, String thumb_url, String thumb_storage_uri, String text, Object timestamp) {
this.author = author;
this.full_url = full_url;
this.text = text;
this.timestamp = timestamp;
this.thumb_storage_uri = thumb_storage_uri;
this.thumb_url = thumb_url;
this.full_storage_uri = full_storage_uri;
}
现在一切都很好。当我从我的存储库类中的观察者检索数据时,我的问题出现了:
@Override
public Observable<List<Post>> getPosts(final String groupId){
return Observable.fromAsync(new Action1<AsyncEmitter<List<Post>>>() {
@Override
public void call(final AsyncEmitter<List<Post>> listAsyncEmitter) {
final ValueEventListener PostListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
final List<Post> postList = new ArrayList<>();
Log.e("Count ", "" + snapshot.getChildrenCount());
//For every child, create a Post object
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Post post = postSnapshot.getValue(Post.class);
Log.e("new post added ", postSnapshot.getKey());
//Set the databaseReference to the object, which is needed later
post.setRef(postSnapshot.getKey());
postList.add(post);
}
listAsyncEmitter.onNext(postList);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("The read failed: ", databaseError.getMessage());
}
};
//Remove listener when unsuscribe
listAsyncEmitter.setCancellation(new AsyncEmitter.Cancellable() {
@Override
public void cancel() throws Exception {
getPostsRef().child(groupId).removeEventListener(PostListener);
}
});
//Set the listener
getPostsRef().child(groupId).addValueEventListener(PostListener);
}
}, AsyncEmitter.BackpressureMode.BUFFER);
}
有了这个观察器,我已经管理了所有的侦听器和数据调用,我唯一的问题是这些行:
//Set the databaseReference to the object, which is needed later
post.setRef(postSnapshot.getKey());
我认为将引用设置为Post模型中的一个新字段并不是一个好的做法,它应该等于我的firebase Json树。所以我的问题是:创建两个不同的模型是一个好的实践吗?一个类似于“dbPost”和“PostEntity”。一个是firebase值,另一个是dbPost中的构建器和我要保存的新字段(dbReference和可能的valueListener)?