Skip to content

Instantly share code, notes, and snippets.

@jgololicic
Last active January 12, 2018 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgololicic/c2444e8948d509cd619ee5e7e84d97ad to your computer and use it in GitHub Desktop.
Save jgololicic/c2444e8948d509cd619ee5e7e84d97ad to your computer and use it in GitHub Desktop.
RxJs - Multicast, Public, Share, RefCount

RxJs - Multicast, Public, Share, RefCount

reference: https://blog.angularindepth.com/rxjs-how-to-use-refcount-73a0c6619a4e

Multicasting

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

The publish operator is a thin wrapper around the multicast operator. It calls multicast, passing a Subject (instance and not a factory function).

Specialised Subjects

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

The share operator is similar to using the publish operator and calling refCount. However, share passes a factory function to multicast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment