4
votes

Currently, I am stuck in a problem with Firebase Observable joins.

I do not really know which is the best way to get my data from different objects and join them together.

My data structure:

users {
    userid1 {
        conversationid: id
        ...
    },
    userid2 {
       ...
    }
}

conversations {
    conversationid {
        ...
    }
}

Now I want to get all conversations of the current user. To get the current user id I'll subscribe to the auth Observable like this:

 this.af.auth.subscribe(auth => {
    console.log(auth.uid);
 });

As next I need the user's child object to get the conversation id. I'm doing that like this:

 //needs the userid from Observable on top 
 this.af.database.object('/users/' + auth.uid)
     .map(
         user => {
             console.log(user.conversationid);
         }
      )
      .subscribe();

And the same for the conversations:

//needs the conversationid from the second Observable 
this.af.database.list('/conversations/' + user.conversationid)
    .subscribe();

As you can see, there are 3 Observables. I know it's possible to nest them, but in my project could this happen up to 5 times.

Is it possible to get the conversations without nesting 3 Observables?

1

1 Answers

5
votes

You could do something like this:

let combined = this.af.auth

    // Filter out unauthenticated states

    .filter(Boolean)

    // Switch to an observable that emits the user.

    .switchMap((auth) => this.af.database.object('/users/' + auth.uid))

    // Switch to an observable that emits the conversation and combine it
    // with the user.

    .switchMap((user) => this.af.database
        .list('/conversations/' + user.conversationid)
        .map((conversation) => ({ user, conversation }))
    );

// The resultant observable will emit objects that have user and
// conversation properties.

combined.subscribe((value) => { console.log(value); });