Firestore的Android存储库模式
作者:互联网
为了更好地分离问题,我想实现一个存储库,该存储库处理所有Firestore交互.
目前,我的代码如下所示:
UserRepository:
public class UserRepository {
private static final String TAG = "UserRepository";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference usersRef = db.collection("users");
public Task<DocumentSnapshot> get(String email) {
DocumentReference docRef = usersRef.document(email); // Users are referenced by email
Log.d(TAG, "Checking DocumentReference exists for: " + email);
return docRef.get();
}
}
主要活动
final UserRepository userRepository = new UserRepository();
userRepository.get(currentUser.getEmail()).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Log.d(TAG, "DocumentSnapshot got");
// Do something with user
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "Could not get DocumentReference", e);
}
});
用户是POJO
我要实现的是一个存储库,它不是Task而是返回Task,如下所示:
public Task<User> get(String email) {
DocumentReference docRef = usersRef.document(email);
/* Convert and return task? */
}
然后可以像往常一样使用它,在MainActivity中附加一个侦听器.恐怕我有点缺乏并发技巧,但我认为无需同步就可以实现.您能给我一个关于如何实现这一目标的提示吗?
提前致谢!
解决方法:
实际上,使用Continuation解决方案非常简单.我不确定任务链是否是我真正想要的,但这似乎是一个很好的解决方案.现在,get方法如下所示:
public Task<User> get(String email) {
DocumentReference docRef = getDocumentReference(email);
return docRef.get().continueWith(new Continuation<DocumentSnapshot, User>() {
@Override
public User then(@NonNull Task<DocumentSnapshot> task) throws Exception {
return task.getResult().toObject(User.class);
}
});
}
编辑:
根据请求,我创建了一个包含实现的要点:
Firestore Repository Gist
标签:firebase,concurrency,repository-pattern,google-cloud-firestore,android 来源: https://codeday.me/bug/20191109/2012284.html