When to use RACReplaySubject vs. RACMulticastConne

2019-03-08 21:19发布

问题:

Using ReactiveCocoa, there seem to be two ways to have subscribers receive the same values from a signal, rather than re-triggering whatever operation generates those values: Via RACReplaySubject or RACMulticastConnection.

Here are the header docs for RACReplaySubject:

A replay subject saves the values it is sent (up to its defined capacity) and resends those to new subscribers. It will also replay an error or completion.

And for RACMulticastConnection:

A multicast connection encapsulates the idea of sharing one subscription to a signal to many subscribers. This is most often needed if the subscription to the underlying signal involves side-effects or shouldn't be called more than once.

The multicasted signal is only subscribed to when -[RACMulticastConnection connect] is called. Until that happens, no values will be sent on signal. See -[RACMulticastConnection autoconnect] for how -[RACMulticastConnection connect] can be called automatically.

Note that you shouldn't create RACMulticastConnection manually. Instead use -[RACSignal publish] or -[RACSignal multicast:].

Can someone provide simple guidelines as to when you would use RACReplaySubject or RACMulticastConnection?

回答1:

Actually, they're not mutually exclusive, and can even be used together.

The main purpose of RACMulticastConnection is to subscribe to a base signal, and then multicast that subscription to any number of other subscribers, without triggering the base signal's side effects multiple times.

RACMulticastConnection accomplishes this by sending values to a private RACSubject, which is exposed via the connection's signal property. Subscribers attach to the subject (which doesn't cause any side effects), and the connection forwards all of the base signal's events there.

There are a few different methods to create a connection:

  • The -publish creates a connection with a plain RACSubject. This subject will not replay previous values to new subscribers.
  • The -multicast: method creates a connection with a subject of your choice. You could decide to use a RACReplaySubject here.
  • The -replay, -replayLast, and -replayLazily methods are conveniences for creating a connection with a RACReplaySubject, and then also automatically connecting to it.

If in doubt, -replayLazily will probably do what you want, because it saves all values and only triggers any side effects (or starts any work) when the returned signal receives a subscription.