问题
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