1
votes

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]?

1

1 Answers

2
votes

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.