Search code examples
angularionic2rxjs

Observable.forkJoin is not working


I've instantiated two Observable objects:

const observable1 = new Observable.create(observer => observer.next(1)); 
const observable2 = new Observable.create(observer => observer.next(2));  
Observable.forkJoin([observable1, observable2]).subscribe(res => console.log(res));

The above forkJoin() is not working even though each of observable.subscribe() is working.

Any thoughts on this?

Thanks


Solution

  • forkJoin waits for all input streams to complete before emitting a resulting value. Since you don't complete observables, it never emits anything. Also, you don't need new with Observable.create and you can import forkJoin directly - no need to use it on Observable. Change your implementation to this:

    import { forkJoin } from 'rxjs/observable/forkJoin';
    import { Observable } from 'rxjs/Observable';
    
    const observable1 = Observable.create(observer => { observer.next(1); observer.complete() });
    const observable2 = Observable.create(observer => { observer.next(2); observer.complete() });
    
    forkJoin([observable1, observable2]).subscribe(res => console.log(res));
    

    For a really great explanation of combination operators, including forkJoin read:

    and here's the link directly to the explanation of forkJoin operator.