问题描述
如果我希望订阅者最初至少获得 X,我是否可以将 startWith( X ) 用于现有的 Observable:
If I want subscribers to initially get at least X, can I use startWith( X ) for an existing Observable:
streamFromLibrary.startWith( X ).subscribe( myHandler );
//I want myHandler() to not wait until streamFromLibrary produce a value
//but be called instantly with X
还是需要像这样通过中间ReplaySubject(1)?
or it still needs to be carried through intermediate ReplaySubject( 1 ) like this?
let carrier = new Rx.ReplaySubject( 1 );
carrier.next( X );
streamFromLibrary.subscribe( value => carrier.next( value ) );
carrier.subscribe( myHandler );
或者如果没有,是否有其他更优雅的方法将值从现有流传送到订阅中,至少有一个初始/最后一个值?
Or if not, is there any other more elegant way to carry values from existing streams into subscription with at least one initial/last value?
推荐答案
你不需要使用ReplaySubject
,但是你应该知道这两个是不一样的:
You don't need to use ReplaySubject
, however you should know that these two aren't the same:
startWith()
操作符只是在每个观察者订阅时向他们发出一个预设值.
The
startWith()
operator just emits a preset value to every observer when they subscribe.
ReplaySubject(1)
类重新发出最后一个通过它的项目.因此,它向每个观察者发出的第一个值可能会有所不同,具体取决于您推入此 Subject 的内容.
The ReplaySubject(1)
class re-emits the one last item that went through it. So the first value it emits to every observer might not be the same depending on what you pushed into this Subject.
请注意,还有 BehaviorSubject
将其初始值作为参数,然后在每次发射时覆盖它,因此它的工作方式与 ReplaySubject(1)
非常相似.
Note, that there's also BehaviorSubject
that takes its initial value as a parameter and then overrides it with every emission so it works very similarly to ReplaySubject(1)
.
但是有一个重要的区别.当 BehaviorSubject
收到 complete
通知时,它永远不会发出任何东西.另一方面,ReplaySubject
总是向每个观察者重放它的缓冲区,即使它已经收到了 complete
通知.
However there's one important distinction. When BehaviorSubject
receives complete
notification it never ever emits anything. On the other hand ReplaySubject
always replays its buffer to every observer even though it has already received the complete
notification.
这篇关于startWith() 运算符是否将 Observable 转换为 ReplaySubject(1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!