RxJS Sample - Why last event from the source is not emitted - rxjs

From RxJS documentation for sample operator (Rxjs-sample), it says:
Whenever the notifier Observable emits a value or completes, sample looks at the source Observable and emits whichever value it has most recently emitted since the previous sampling, unless the source has not emitted anything since the previous sampling.
However, the following code does not seem to behave appropriately:
Rx.Observable.zip(
Rx.Observable.from(['Joe', 'Frank', 'Bob']),
Rx.Observable.interval(2000)
)
.sample(Rx.Observable.interval(2500))
.subscribe(console.log);
The output is as follows:
[ 'Joe', 0 ]
[ 'Frank', 1 ]
Why does the output not include ['Bob', 2]?

It is the expected behavior. The notifier Observable does not complete when the source Observable completes. It's free to complete whenever; before or after the source Observable. This snippet of the documentation:
Whenever the notifier Observable ... completes
is only referring to the case where the notifier Observable completes before the source Observable. Your notifier Observable:
Rx.Observable.interval(2500)
never completes, so only the values that are emitted while the source Observable is still alive will be taken into account. To draw a rough marble diagram:
Source: -----O-----O-----O|
Notifier: ------O------O------O--...
Only the first two marbles on the notifier Observable will cause sample to emit values. When the source Observable dies, the whole chain is dead and the notifier Observable no longer matters. In fact, I'd bet Rxjs is smart enough to unsubscribe from it so as to not cause a memory leak.

Related

Do RxJS observers always process all events submitted before the observable is completed?

I want to make sure that all events, which were submitted before complete was invoked on the observable, are logged.
I'm aware that operators exist that stop emission of events (takeUntil, etc.) completely.
The question that I have is whether other operators exist which would lead to emissions not being sent if the complete on the subject is sent too 'early'. Are there cases where it would be beneficial to wait with the completion of the observable until the event was handled by the observer?
For example, are there situations (imagine any other RxJS operator instead of the delay) where the following code ...
const subj = new Subject<string>();
subj.pipe(delay(500))
.subscribe((val) => {
console.log(val);
subj.complete();
});
subj.next('1');
... makes more sense than that ...
const subj = new Subject<string>();
subj.pipe(delay(500))
.subscribe((val) => {
console.log(val);
});
subj.next('1');
subj.complete();
... when the subject should only emit one value?
Or is completing the subject immediately after next always safe in such situations?
If there are other factors I'm not aware of (e.g. synchronous vs. asynchronous execution of code) please mention them as well.
In general,
subj.next('1');
subj.complete();
is safe. As far as I know, none of the existing RxJS operators use a completion to cancel/unsubscribe observables early.
That being said, I can easily create such an operator myself. switchMap will cancel currently running inner observables when it receives it's next emission. You could, for example, create a custom operator that unsubscribes and exists early when it receives a complete event.
If your worried about that, however, you're out of luck. No matter what workaround you imagine, I can probably write an operator that will ruin your code. For example filter(_ => false) will stop the 1 from being emitted before the complete in either of the two cases you've described.
In the end, you and your coworkers must write good code (and test!) and RxJS doesn't change that.

difference between forkjoin and combineLatest rxjs

Both are used to join multiple streams.
From this
I am confused between both, I read combineLatest make calls in sync mode and forkJoin calls parallel,
I am trying this
combineLatest([
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000))
]).subscribe(() => console.log(new Date().getTime() - start));
forkJoin([
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000))
]).subscribe(() => console.log(new Date().getTime() - start));
that prints
5004
5014
every time result is arround 5 sec, if combineLatest sends request in sequence then why it is printing duration arround 5 sec.
Is this correct or there is any other difference, any example code?
Both subscribe to all source Observables in parallel and whether they are asynchronous depends only on each source Observable.
So in this use-case you'll get the same result. If you used concat() instead you would see difference because concat() subscribes to sources in sequence one after antother.
The difference between forkJoin and combineLatest is that forkJoin will emit only once when all source Observable emit at least one item and complete while combineLatest will emit every time any of the source Observables emit after they've emitted at least once.

Is it safe/okay to combine take(1) and defaultIfEmpty when subscribing to Observable<boolean>?

I am using the following code to basically ensure that I get a result from an Observable
this.authenticationService.isLoggedIn
.pipe(
take(1),
defaultIfEmpty(false)
)
.subscribe(result => return result);
Somehow it feels wrong to me, maybe because it seems sort of procedural.
Is this method okay? Will this get me in trouble in any way?
If in your code it's fine that this.authenticationService.isLoggedIn completes without an emit - then the code in your question is fine too.
If this.authenticationService.isLoggedIn emits anything at some point of time and completes after - then defaultIfEmpty is redundant.
It all depends on what isLoggedIn does.
It is clear that isLoggedIn returns an Observable.
Now, and Observable can do just 3 things
it can notify, i.e. emit, some data for consumption of Observers which are subscribed
it can raise an error
it can complete
So the first question is: how many times can isLoggedIn notify? Is it just one shot or is it a stream of notifications? If it can emit just one value and then complete, than the take(1) operator is useless.
But there is also the case that isLoggedIn never notifies and just completes. In this case a notification would never be signaled by the observer to its subscriber. Using defaultIfEmpty operator ensures that something is notified even in this case.
So, reading your code I understand that isLoggedIn can behave in these 2 ways
Emit more than once but you are interested only in the first notification
Never notify and just complete, in which case you want false to be returned
If this is not true, it may be the case that your code can be simplified.

RxJS - pausing an Observable until second Observable completes,

I have a scenario where 1 observable listens for events, which should then fire another asynchrounous event, and wait before it runs the next item in the source Observable.
The first observable can be triggered much faster than the the async event, and it must wait for the async event to complete before it takes another item from the 1st observable.
So.. essentially I need to set up a 'queue' from the first observable (as I cant lose the data from source 1)
Source 2 should take 1 item at a time from the queue, run it, remove the item from the queue, and go onto the next item in the queue .
src1- --ev1---ev2---ev3----ev4---ev5--ev6---
src2- --ev1------------ev2-------------ev3--------ev4-------ev5------ev6
--------------async-----------async---------async------async------asyc
I was looking at the RX docs and it seems that pausibleBuffered could be a solution but I noticed it has been removed in RX5, which is what I am using. Can someone give advice as the right way to accomplish this ?
Thanks!
You can use mergeScan to run async operations one by one because it needs the previous async operation’s result to run an async operation.
const src2 = src1.mergeScan((_, value) => doSomething(value));
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeScan

SwitchMap vs MergeMap in the #ngrx example

Below is code from the Ngrx example: https://github.com/ngrx/example-app/blob/master/src/effects/book.ts My question is why in the first #Effect, it uses switchMap while the others use mergeMap. Is that because the first #Effect is dealing with network, and with the switchMap you can cancel the previous network request if it's running?
#Effect() search$ = this.updates$
.whenAction(BookActions.SEARCH)
.map<string>(toPayload)
.filter(query => query !== '')
.switchMap(query => this.googleBooks.searchBooks(query)
.map(books => this.bookActions.searchComplete(books))
.catch(() => Observable.of(this.bookActions.searchComplete([])))
);
#Effect() clearSearch$ = this.updates$
.whenAction(BookActions.SEARCH)
.map<string>(toPayload)
.filter(query => query === '')
.mapTo(this.bookActions.searchComplete([]));
#Effect() addBookToCollection$ = this.updates$
.whenAction(BookActions.ADD_TO_COLLECTION)
.map<Book>(toPayload)
.mergeMap(book => this.db.insert('books', [ book ])
.mapTo(this.bookActions.addToCollectionSuccess(book))
.catch(() => Observable.of(
this.bookActions.addToCollectionFail(book)
))
);
#Effect() removeBookFromCollection$ = this.updates$
.whenAction(BookActions.REMOVE_FROM_COLLECTION)
.map<Book>(toPayload)
.mergeMap(book => this.db.executeWrite('books', 'delete', [ book.id ])
.mapTo(this.bookActions.removeFromCollectionSuccess(book))
.catch(() => Observable.of(
this.bookActions.removeFromCollectionFail(book)
))
);
}
You are correct; switchMap will unsubscribe from the Observable returned by its project argument as soon as it has invoked the project function again to produce a new Observable.
RxJs is incredibly powerful and dense, but its high level of abstraction can sometimes make code hard to understand. Let me debunk the marble diagrams and docs given by #Andy Hole a little and bring them up to date. You may find the marble syntax reference highly valuable to better understand rxjs operators from their tests (at least I found this missing/not highlighted enough in the official docs).
mergeMap
The first line in the diagram is the source Observable which emits (1,3,5) at different times. The second line in the diagram is the prototypical Observable returned by the project function i => ... passed to the .mergeMap() operator.
When the source Observable emits the item 1, mergeMap() invokes the project function with i=1. The returned Observable will emit 10 three times, every 10 frames (see marble syntax reference). The same happens when the source Observable emits item 3 and the project function creates an Observable that emits 30 three times. Note that the result of mergeMap() contains all three elements generated by each Observable returned from project.
switchMap
This is different with switchMap(), which will unsubscribe from the Observable returned by project as soon as it has invoked it again on a new element. The marble diagram indicates this with the missing third 30 item in the output Observable.
In the example you have given, this leads to the cancellation of the pending search request. This is a very nice but hard-to-get-right property, which you get for free by combining switchMap() with cancellable Observables returned by Angular's Http service. This can save you a lot of headaches without worrying about properly handling all the race conditions that typically occur with async cancellation.
You are right.
As you can see, switchMap is used with search functionality. The searchbox in this example is programmed to basically emit a search request when the user enters text in the textbox (with a 350ms debounce or delay).
This means that when the user enters 'har', ngrx sends a search request to the service. When the user enters another letter 'r', the previous request is canceled (since we are not interested in 'har' anymore, but 'harr').
It is very nicely shown in the marble diagrams provided in another answer.
In mergeMap, the previous Observables are not canceled and therefore '30' and '50' are mixed together. Using switchMap, only the 5s are emitted, because the 3's are canceled.
mergeMap
Projects each source value to an Observable which is merged in the output Observable.
Maps each value to an Observable, then flattens all of these inner Observables using mergeAll.
switchMap
Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.
Maps each value to an Observable, then flattens all of these inner Observables using switch.
Source: ES6 Observables in RxJS
You don't want an API save data request to cancel. That is why you would use mergeMap. A search query can be thrown away, no loss of data, and the user might be editing their query and are not interested in the data for the old one. Hence switchMap.
Yes, if you are no longer concerned with the response of the previous request when a new Input arrives switchMap is a suitable operator than mergeMap.

Resources