简体   繁体   中英

rxjs does a cold obs store all messages

when reading an intro to rxjs I came read the following and was a bit concerned

the second subscription will restart the sequence from the first value.

how does it start from the first value? does it store all values in memory? That could be a real problem for me as I am using it in a worker/service that will stay running. So if it's holding on to them all than I'm headed for a massive blow up. Thanks, R

Standard subscriptions do not buffer any values. Some operators (and subjects) do need to buffer some values to implement their behaviour (and that buffer can be unbounded) but that is a problem distinct from the hot vs. cold dichotomy.

The short explanation is that the (cold) source observable (the most upstream observable) knows how to generate its values but only does so when he has a subscriber. And he generates the same values for all subscribers. So there is no buffering, more like regeneration of values. For instance, Rx.Observable.range(1,10) knows which values it has to generate, and generate them anytime there is a subscriber. It does not keep a buffer with 1,2,3...10 in memory, just 1 and 10 and iterates in between to generate the values. Same goes for most of cold observables, they have a value generating function associated to them, and that function is reexecuted anew for each subscriber.

If you want to switch to a behaviour for observables in which they push their values as soon as they receive/generate them, to all existing subscribers at the moment of reception/generation, you have to convert your cold observable to a hot one.

For a more in-depth explanation, have a look at the illustrated subscription and data flows corresponding to hot and cold observables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM