Does startWith() operator turns Observable into ReplaySubject(1)?

守給你的承諾、 提交于 2019-12-11 07:58:26

问题


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

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?


回答1:


You don't need to use ReplaySubject, however you should know that these two aren't the same:

  • The startWith() operator just emits a preset value to every observer when they subscribe.

  • 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.

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).

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.



来源:https://stackoverflow.com/questions/45302580/does-startwith-operator-turns-observable-into-replaysubject1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!