rejkid
rejkid

Reputation: 345

RxJS Observable and subscribe method

Does RxJS Observable remove an item after emitting it (to Observer)?

Upvotes: 2

Views: 1023

Answers (1)

Joshua McCarthy
Joshua McCarthy

Reputation: 1852

One of the tricky aspects of RxJS to keep in mind is factoring in time. By default, when an observable emits a value, an existing observer will receive that value. If an observer subscribes to an observable after it has emitted a value, it will not receive it because it was a "late" subscriber.

Also, by default an observable can only have one subscriber. If you want to have multiple subscribers to one observable, you should use the share() operator. Subjects (and their sub-classes) can share with multiple subscribers by default. Even then, you need to keep timing in mind. You must consider when the source observable emits a value, and when all observers are actively subscribed to receive that value.

Lastly, you can also cache emitted values, meaning any late subscribers will still receive those values upon subscription. With observables, you can use the shareReplay(n) where n is the number of values you want to replay to any new subscribers.

BehaviorSubjects work similarly in that by default it will emit its last single value to any observers the moment they subscribe. ReplaySubject also does this where you can pass in n number of emitted values.

Upvotes: 1

Related Questions