reference: https://blog.angularindepth.com/rxjs-how-to-use-refcount-73a0c6619a4e
multicast takes Subject and returns ConnectableObservable which offers two methods:
- connect()
- refCount()
When connect is called, the multicast connects the Subject to Source observable. When Source observable completes, multicast unsubscribes the Subject from it.
When RefCount is called, the multicast manages connections of Subject to Source automatically. When number of subscriptions to Subject grows from 0 to 1, multicast automatically connect the Subject to the Source. When number of subscriptions drop from 1 to 0, the multicast automatically unsubscribes Subject form the source.
Subjects are not reusable.
Insetead of passing a Subject to the multicast, we can pass factory function which provides Subjects
const obs = source.multicast(() => new Subject<any>()).refCount()
The publish operator is a thin wrapper around the multicast operator. It calls multicast, passing a Subject (instance and not a factory function).
The specialised subjects that the publish variants use include:
- the BehaviorSubject - Initialises value, which can be used for subscribers which subscribe before source emits first value.
- the ReplaySubject - ReplaySubject will replay the specified number of next notifications whenever an observer subscribes.
- the AsyncSubject - Emits only the last value, once the source completes (.publishLast operator)
the corresponding operators would be
- .publishBehaviour
- .publishReplay
- .publishLast
const obs = source.publish().refCount()
const obs = source.publishBehaviour().refCount()
const obs = source.publishReplay().refCount()
const obs = source.publishLast().refCount()
The share operator is similar to using the publish operator and calling refCount. However, share passes a factory function to multicast.