Zbigniew Malinowski
Zbigniew Malinowski

Reputation: 1064

Make sure that all the items emitted by a hot observable are consumed exactly once

I have:

  1. A source that is a hot observable that at some point emits one item and completes
  2. Multiple observers that keep subscribing/unsubscribing to/from the source (but at most one can be subscribed at the same time)

I would like to transform the source to an observable that makes sure the item is consumed exactly once by an observer. Observers that subscribe later should be only notified that the item has been consumed (completion event).

Expected behaviour:

1) Emission from the source before an observer subscribes

--O-|------>  (source)

-----^-O-|->  (observer)

2) Emission from the source after an observer subscribes

------O-|->  (source)

--^---O-|->  (observer)

3) Subscription after item has been consumed

-O-|------->  (source)

-^-O-|----->  (observer1 - consumes the item)

------^-|-->  (observer2 - is notified that the item has been consumed)

What is the simplest and most elegant way to achieve such behaviour?

Upvotes: 0

Views: 49

Answers (1)

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

Use a BehaviorSubject. This describes its behavior exactly.

Upvotes: 1

Related Questions