I'm wondering what are the differences between Observable.combineLatest and Observable.forkJoin?
As far as I can see, the only difference is forkJoin expects the Observables to be completed, while combineLatest returns the latest values.
Not only does forkJoin require all input observables to be completed, but it also returns an observable that produces a single value that is an array of the last values produced by the input observables. In other words, it waits until the last input observable completes, and then produces a single value and completes.
In contrast, combineLatest returns an Observable that produces a new value every time the input observables do, once all input observables have produced at least one value. This means it could have infinite values and may not complete. It also means that the input observables don't have to complete before producing a value.
forkJoin - When all observables are completed, emit the last emitted value from each.
combineLatest - When any observable emits a value, emit the latest value from each.
Usage is pretty similar, but you shouldn't forget to unsubscribe from combineLatest unlike forkJoin.
combineLatest(...)
runs observables in parallel, emitting a value each time an observable emits a value after all observables have emitted at least one value.
forkJoin(...)
runs observables in parallel, and emits a single value once all observables have completed.
Consideration for error handling:
If any of the observables error out - with combineLatest it will emit up to the point the error is thrown. forkJoin will just give back an error if any of the observables error out.
Advanced note: CombineLatest doesn't just get a single value for each source and move onto the next. If you need to ensure you only get the 'next available item' for each source observable you can add .pipe(take(1)) to the source observable as you add it to the input array.
There is a situation in Angular which would explain it better. Assume there is a change detection in Angular component, so the latest value is changed. In the pipe and tap methods of combineLatest, the code will be triggered as well. If the latest value is changed N times by the change detection, then the tap methods is also triggered N times as well.
Related
In my application, I need to initiate a burst of long-running http requests which optimally should be allowed to resolve concurrently. The results must be concatenated into a single observable for evaluation downstream.
Merging these observables using mergeMap allows for this concurrency, but this unfortunately does not guarantee order of the results. ConcatMap guarantees order of the values emitted by the output, but it appears that the mapping operation for a given request is not executed until after its predecessor is completed, limiting concurrency to a single request at once (I'm not certain this is how it works but it would explain the result).
Before I start writing a custom operator, I thought I would ask: what is the best way to merge the results from a batch of requests, each returning an observable, while enabling concurrency and guaranteeing order of the results in the output observable?
As the comment said, the forkJoin / combineLatest (you would see the difference between these two by observing their marble diagram), you can get what you want.
How forkJoin works is, it will subscribe to EVERY observables parameter, wait until ALL observables complete, and then emit the value (order is determined by the order of parameter). https://rxjs.dev/api/index/function/forkJoin
And yes, forkJoin is not a pipeable operator, because it's not. It will return an observable. So you can use it with switchMap/other higher order mapping.
Example
const studentsAndTeachers = school$.pipe(
map(school=> school.id),
switchMap(id => forkJoin(http.post('getStudents', id), http.post('getTeachers, id))
)
studentsAndTeachers will get you a tuple ([]) of students and teachers [[students], [teachers]]
I have two observables combined with combineLatest([this.currentPageIndex$, this.currentStoryIndex$]), they represent a shelv with books, first observable emits current book index, second - page of current book.
I have logger service, logging current page and current book number
When page changes everything is fine, but when i switch to a new book both observables emits values: one from current page which become 1 and another is new book number, and logger service logs twice, is there any way to prevent that double logging?
addition, books can have single page
combineLatest works something like:
Wait for all input observable to emit 1 value. After that emit the values.
Every time an observable emits a value, emit that value along with the other values.
So yes, you'll have duplicates there.
You can use concat instead, if you care about the order of the emissions. If not, you can use merge.
here is the example
forkJoin(
{
google: ajax.getJSON('https://api.github.com/users/google'),
microsoft: ajax.getJSON('https://api.github.com/users/microsoft'),
users: ajax.getJSON('https://api.github.com/users')
}
)
.subscribe(console.log);
There are three API calls in the forkjoin. I am confused about, is all API calls will run one by one. Or it runs all calls at the same time and waits for responses?
In the scenario you describe, forkJoin acts like Promise.all - all calls are made at the same time (not one by one), once all of them return, forkjoin will fire once with the return value for those calls, here is the definition from the official site:
Accepts an Array of ObservableInput or a dictionary Object of ObservableInput and returns an Observable that emits either an array of values in the exact same order as the passed array, ...
Please note that if one these were an observable (e.g. interval), and it fired three times before the other two return, only the last value would be emitted
See picture below from the official site:
I am using marble diagrams to show the output of two different observables. The first uses a switchmap, that pipes into another switchmap. The second observable has two switchmaps in the same pipe.
Here are the two marble flows:
The first uses switchmaps inside inner piping
https://rxviz.com/v/38MavX78
The second uses switchmaps inside a single pipe
https://rxviz.com/v/9J9zNpq8
How come they have different outcome?
My understanding is that switchMap does what it sounds like from the name - it switches the Observable chain from one Observable (the "outer" one) to another (the "inner" one). If the outer Observable emits before the inner one completes, then switchMap will unsubscribe from that inner Observable, and re-subscribe, effectively "cancelling" the first subscription. Docs here.
Now in your first case, you have nested the switchMap to grandchildren$ INSIDE the switchmap to children$. Therefore when parent$ emits the second time, it will cancel the switch to children$ AND the switch to grandchildren$, since grandchildren$ is a part of children$ (nested within it).
However, in the second case, you do not have them nested. Therefore when parent$ emits the second time it will indeed cancel the children$ subscription, but children$ will not emit anything when that happens, leaving the chain further down untouched. Therefore grandchildren$ keeps emitting until children$ actually emits something, which will be 1000ms after it was re-subscribed to when parent$ emitted.
Hopefully that makes sense.
I have several observables request.
Each observable request is recursive call and when there is no more data, it will call EMPTY.
for example:
request1 = recursive observable call
request2 = recursive observable call
request3 = recursive observable call
Then i use forJoin
forJoin(request, request2, request3).subscribe();
The forkJoin will callback with complete when anyone of them finish. It actually not wait for all observables complete.
I check the rxjs document, it mention
When all observables complete, emit the last emitted value from each.
As I don't care these observables return value, so it would not emit value to the forkJoin observer. Then i found that in this case if only one complete, forkJoin observer is notified with complete.
Is this the observable limitation that i do need to emit value to able to wait for all observables complete?
Thanks a lot.
It is by design.
Reference here:
forkJoin short circuits if one of the streams completes without emitting a value.
Since EMPTY just emits 'complete' and nothing else, forkJoin will complete right there.
Actually, the other non-empty observables inside forkJoin will still be subscribed, but since forkJoin may complete before them (depends on when did the EMPTY appear in forkJoin), you may not be able to handle them inside the forkJoin's complete function.