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:
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 => {
The forkJoin will subscribe to the passed observables, by making the HTTP GET requests. If any input observable errors at some point, forkJoin will find the error as well and all other observables will be immediately unsubscribed.
forkJoin is an operator that takes any number of input observables which can be passed either as an array or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed), then the resulting stream will complete immediately.
As forkJoin only completes when all inner observables complete, we must be mindful if an observable never completes.
concat() which will handle each observable in sequence.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With