Observable.forkJoin() doesn't execute

TheUnreal picture TheUnreal · Oct 28, 2016 · Viewed 26.4k times · Source

I have the following code:

//Loop: For each user ID/Role ID, get the data
userMeta.forEach((businessRole) => {
  Observable.forkJoin(
    af.database.object('/roles/'+businessRole.$value),
    af.database.object('/users/'+businessRole.$key)
  ).subscribe(
    data => {
      console.log("Data received");
      data[1].role = data[0];
      this.users.push(data[1]);
    },
    err => console.error(err)
  );

I am trying to subscribe to a result of 2 observables using forkJoin.

For some reasons, the "Data received" message is not shown.

My userMeta variables looks fine at console.log:

enter image description here

What's wrong?

Update: the following code does not return anything either

let source = Observable.forkJoin(
        af.database.object('/roles/'+businessRole.$value),
        af.database.object('/users/'+businessRole.$key)
    );
    let subscription = source.subscribe(
      function (x) {
    console.log("GOT: " + x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

What I actually trying to do is improve the performance of the following code:

//Subscription 3: role ID to role Name
        af.database.object('/roles/'+businessRole.$value)
        .subscribe((roleData) => {
        //Subscription 4: Get user info
        af.database.object('/users/'+businessRole.$key).subscribe(user => {

Answer

martin picture martin · Oct 28, 2016

forkJoin() requires all source Observables to emit at least once and to complete.

This following demo completes as expected:

const source = forkJoin(
  from([1,2,3]),
  from([9,8,7,6])
).subscribe(
  x => console.log('GOT:', x),
  err => console.log('Error:', err),
  () => console.log('Completed')
);

Live demo: https://stackblitz.com/edit/rxjs-urhkni

GOT: 3,6
Completed

Jan 2019: Updated for RxJS 6