Reputation: 3924
So here is my Firebase structures look like:
firebase-url/users/
/user-id/
posts
profile
relations
/user-id/
posts
profile
relations
every user has his own posts, let's say there are 2 users. user A and B. if A has a relationship with B, then both could see each other posts and listen for the updates. the situation is simple when A listen to B posts, but A may has n relations with other users like B,C,D ..etc.
I checked other threads like this and this but there is no a clear simple solution for my problem, for example the first thread was about listening to constant number of childs, which is not a big problem.
how could A listen to multiple user posts updates? specially when users number is big and more than 10 or 20.
Upvotes: 2
Views: 981
Reputation: 7368
Listen for value events
ValueEventListener onDataChange() Read and listen for changes to the entire contents of a path.
You can use the onDataChange() method to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null.
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
Upvotes: 0
Reputation: 1
To achieve this you need to remodel your database. Here is how it can be done.
firebase-url
|
--- users
| |
| ---- userId_1
| | |
| | ---- userName: "John"
| | |
| | ---- userAge: 30
| | |
| | ---- posts
| | |
| | ---- post_1 : true
| | |
| | ---- post_2 : true
| |
| ---- userId_2
| |
| ---- userName: "Anna"
| |
| ---- userAge: 25
| |
| ---- posts
| |
| ---- post_3 : true
| |
| ---- post_4 : true
|
---- posts
|
---- postId_1
|
---- postName: "post_1"
|
---- users
|
---- userId_1: true
|
---- userId_2: true
In this way you can query your database very simple to display all the users that have access to a single post: firebase-url/posts/postId/users/
and also all the posts that a user can read: firebase-url/users/userId/posts/
Hope it helps.
Upvotes: 3