2017-10-05 55 views
4

當用戶在我的應用中查看他的朋友列表時,我希望該應用通過列表中的每個用戶並從Cloud Firestore中檢索他的最新信息。Cloud Firestore - 從多個位置獲取文檔

這是我當前的代碼:

final CollectionReference usersRef= FirebaseFirestore.getInstance().collection("users"); 

      usersRef.document(loggedEmail).collection("friends_list").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { 
       @Override 
       public void onSuccess(QuerySnapshot documentSnapshots) { 
        if (!documentSnapshots.isEmpty()){ 


         for (DocumentSnapshot friendDocument: documentSnapshots) { 

          usersRef.document(friendDocument.getString("email")).get().addOnSuccessListener 
            (new OnSuccessListener<DocumentSnapshot>() { 
           @Override 
           public void onSuccess(DocumentSnapshot documentSnapshot) { 
            User friend=documentSnapshot.toObject(User.class); 
           friendsList_UserList.add(friend); 

           } 
          }); 

         } 


         ///... 

        } 

        else 
         noFriendsFound(); 

       } 

這是我想要的過程的說明:

enter image description here

正如你看到的,我可以得到每個用戶的信息這樣,但我找不到方法來聽這個過程,並繼續,當我有關於用戶的列表中的所有朋友的信息。

是我能一次獲得所有朋友信息的一種方式嗎?

回答

2

Firestore不直接支持像您要求的連接。

您可以使用QuerySnapshot中的getDocumentChanges構造一個鏈接的收聽者,以跟蹤您應該聽哪些朋友。

試想一下,如果你保持地圖的朋友聽衆註冊的這樣

Map<String, ListenerRegistration> friendListeners = new HashMap<>(); 

然後,你可以註冊這樣的事情:

usersRef.document(loggedEmail).collection("friends_list") 
    .addSnapshotListener(new EventListener<QuerySnapshot>() { 
     @Override 
     public void onEvent(QuerySnapshot snapshot, FirebaseFirestoreException error) { 
     for (DocumentChange change : snapshot.getDocumentChanges()) { 
      DocumentSnapshot friend = change.getDocument(); 
      String friendId = friend.getId(); 
      ListenerRegistration registration; 
      switch (change.getType()) { 
      case ADDED: 
      case MODIFIED: 
       if (!friendListeners.containsKey(friendId)) { 
       registration = usersRef.document(friendId).addSnapshotListener(null); 
       friendListeners.put(friendId, registration); 
       } 
       break; 

      case REMOVED: 
       registration = friendListeners.get(friendId); 
       if (registration != null) { 
       registration.remove(); 
       friendListeners.remove(friendId); 
       } 
       break; 
      } 
     } 
     } 
    }); 

但請注意,這實際上可能不是一個好主意。您可能更願意將足夠的信息放入friends_list文檔中,只有在您深入瞭解該朋友的詳細信息時,才需要加載實際的朋友用戶文檔。

相關問題