rxjs的第一个运算符被反复调用? [英] rxjs first operator is being repeatedly called?
问题描述
如果我使用的话,每3秒钟将有2条打印到控制台:
If I use, 2 gets 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))
如果我使用的话,只有2次打印到控制台:
If I use, 2 gets printed to the console only one time:
Rx.Observable.interval(3000)
.mergeMap(() => Rx.Observable.of(3))
.concatMap(()=>Rx.Observable.of(2))
.first(x=>x == 2)
.subscribe((x)=>console.log(x))
区别在于我链接了第一个运算符的位置,但是我不了解链接的流程.我认为在这两种情况下,由于我的可观察值为2,所以它应该只打印2次.
The difference is where I chained the first operator, but I don't understand the flow of the chain. I thought in both cases, it should only print 2 once since I have an observable of 2.
推荐答案
您对first()
运算符感到困惑. first()
的定义是:
You are confused with the first()
operator. The definition of first()
is:
返回满足谓词条件的可观察序列的第一个元素,如果不存在该元素,则返回默认值.如果未提供默认值,则将调用onError.
Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. If no default value is given, then onError will be called.
注意单词可观察到的序列,又名流.两种情况的区别如下:
Note the word observable sequence, aka stream. The difference of the two scenarios are as follow:
您的first()
应用于返回值2的可观察对象.Observable.interval()
流不执行任何操作,该流每3秒不断发出一个事件.这就是为什么您的控制台永不停止记录的原因.
Your first()
is applied to an observable that returns a value 2. Nothing is done to the Observable.interval()
stream, which keeps on emitting an event every 3 seconds. That is why your console never stops logging.
first()
应用于一个Observable.interval()
,该Observable.interval()
连续 每3秒发出一次事件.因此,一旦找到满足条件的x===2
,您的first()
运算符就基本将其斩波(或停止该序列).当条件满足时,流结束,然后返回该序列的FIRST元素.因此,您的控制台仅记录一次.
The first()
is applied to an Observable.interval()
that continuously emits an event, every 3 seconds. Hence, your first()
operator basically chops the sequence (or stop it) as soon as it finds the fulfilling condition, which is x===2
. When the condition is met, the stream ends, it then returns the FIRST element of that sequence. Hence your console only logs one time.
这篇关于rxjs的第一个运算符被反复调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!