Rxjs first statement being called repeatedly?
If I use, 2 is printed to the console every 3 seconds:
Rx.Observable.interval(3000)
.mergeMap(() => Rx.Observable.of(3))
.concatMap(()=>Rx.Observable.of(2).first(x=>x == 2))
.subscribe((x)=>console.log(x))
If I use, 2 is printed to the console only once:
Rx.Observable.interval(3000)
.mergeMap(() => Rx.Observable.of(3))
.concatMap(()=>Rx.Observable.of(2))
.first(x=>x == 2)
.subscribe((x)=>console.log(x))
The difference is where I attached the first statement, but I don't understand the flow of the chain. I thought it should only print 2 times in both cases, since I observe 2.
source to share
You are confused with the operator first()
. Definition first()
:
Returns the first element in the observed sequence that satisfies a condition in a predicate, or a default value if no such element exists. If no default is specified, onError is raised.
Pay attention to the observed sequence of words, in other words. The difference between the two scenarios is as follows:
Scenario 1:
Yours first()
applies to an observable that returns 2. Nothing is done for a thread Observable.interval()
that continues to emit an event every 3 seconds. This is why your console never stops registering.
Scenario 2:
first()
applies to Observable.interval()
that continuously emits an event every 3 seconds. Hence, your statement first()
basically interrupts (or stops) the sequence as soon as it detects an execution condition that x===2
. When the condition is met, the stream ends, then it returns the FIRST element of this sequence. Hence your console only registers once.
source to share