I am trying to use Observable.forkJoin
and the subscribe handler is never getting hit. The forkJoin operator is working for me in other parts of my app and the only difference I can think of in the non-working scenario is that the observables are being created from BehaviorSubject
objects using its asObservable()
function.
This subscribe gets hit
let obs = Observable.of(1);
Observable.forkJoin(
obs
).subscribe(data => {
console.log(data);
});
This one does not
let bs = new BehaviorSubject<number>(1);
let obs = bs.asObservable();
Observable.forkJoin(
obs
).subscribe(data => {
console.log(data);
});
Of course in my real use case there is more than one obseravble which is why I'm using forkJoin in the first place.
Is there something else that needs to be done to BehaviorSubject to make it work with forkJoin?
UPDATE:
After investigating the RxJs docs a bit more I realized that the Observable.combineLatest
was much better suited to my need than forkJoin
... Link here in case any comes across this SO post:
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-combineLatest
Be aware that if any of the inner observables supplied to forkJoin error you will lose the value of any other observables that would or have already completed if you do not catch the error correctly on the inner observable.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.
The RxJS forkJoin() operator is a join operator that accepts an Array of ObservableInput or a dictionary Object of ObservableInput and returns an Observableand then waits for the Observables to complete and then combine last values they emitted.
forkJoin takes a number of input observables and waits for all passed observables to complete. Once they are complete, it will then emit a group of the last values from corresponding observables. The resulting stream emits only one time when all of the inner streams complete.
The issue is that forkJoin
joins the observables when they complete.
In your first snippet, you are creating an observable using of
- which, upon subscribe
, immediately emits a value and then completes.
In your second snippet, the BehaviorSubject
does not complete. If you were to call complete
, you would see the value logged to the console:
let bs = new BehaviorSubject<number>(1);
let obs = bs.asObservable();
Observable.forkJoin(
obs
).subscribe(data => {
console.log(data);
});
bs.complete();
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