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.
Related
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.
In Reactivex.IO documentation it was stated that
You can ignore the final n items emitted by an Observable and attend only to those items that come before them, by modifying the Observable with the SkipLast operator.
and the diagram from http://reactivex.io/documentation/operators/skiplast.html
My Expectations: SkipLast will read the entire Observable till it meets the OnCompleted and then generates a new Observable with the timings as the Original one but skipping the Last ones.
My Doubt: How does SkipLast Operator know that "3" is that Last 2nd Item from the Observable? Without seeing the OnCompleted how can it tell the Last nth Item?
Thanks #PanagiotisKanavos, #akarnokd for Valuable comments.
It is internally implemented with a Queue of Fixed Size. Take the items from the Sequence and Enqueue them, when the Queue is full and Starts to Overflow Dequeue the item & Enqueue the latest value and Send to OnNext(dequeued_value), so when OnCompleted Reached you will not Send the Cached items and just call OnCompleted. By this last N cached items are Skipped.
From a source code if skipLast(N) is used, then N messages is kept in the this._ring array. As soon N+1 arrived first message is emitted, N+2 arrived => second messages is emitted etc.
All over the Rx.Net literature there are references to what is commonly know as the temperature of an observable.
There are cold observables (like the ones created by Observable.Interval() and similar factory methods), which will create side effects every time that a new Subscription is created.
On the other side of the spectrum there are hot observables (like Subject<T>) which will onboard new subscriptions as they come.
There are also warm observables, like the ones returned by RefCount() which will execute the initialisation every time one subscription is created, but only if there was no other active subscription. The behaviour of these warm observables is explained here by Dave Sexton:
Alternatively, you can call Publish then RefCount to get an IObservable that is shared among multiple consecutive observers. Note that this isn't truly a hot observable - it's more like a warm observable. RefCount makes a single subscription to the underlying observable while there's at least one observer of your query. When your query has no more observers, changing the reference count to 0, the underlying subscription is disposed. If another observer subscribes to your query later, moving the reference count from 0 to 1 again, then RefCount makes a new subscription to the underlying observable, causing subscription side-effects to occur again.
Are there any other temperatures that one should be aware of? Is it possible to obtain programmatically the temperature of an Observable?
Easy question first:
Is it possible to obtain programmatically the temperature of an Observable?
No. Best you can do is subscribe and see what happens.
The observable 'contract' specifies that when you subscribe to an observable you get zero or more OnNext messages, optionally followed by either one OnCompleted or one OnError message. The contract doesn't specify anything about how multiple or earlier/later subscribers are treated, which is what observable 'temperature' is mostly concerned with.
Are there any other temperatures that one should be aware of?
I wouldn't even think of it in such concrete or discrete terms as you have specified.
I think of it in terms of on-subscribe effects: The coldest of observables have all their effects happen on subscribe (like Observable.Return(42)). The hottest of observables have no effects happening on subscribe (new Subject<int>()). In between those two poles is a continuum.
Observable.Interval(TimeSpan.FromMilliseconds(100)) for example will emit a new number every 100 milliseconds. That example, unlike Observable.Return(42), could be mostly 'warmed-over' via .Publish().RefCount(): The first subscriber starts the numbers, but the second subscriber will see the only the latest numbers, not starting from 0. However, if instead of .Publish() you did .Replay(2).RefCount(), then you have some on-subscribe effects going on. Do the Publish and Replay observables have the same 'temperature'?
TL;DR: Don't focus on the classifications that much. Understand the difference between the two and know that some observables have colder properties and some have warmer ones.
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.