为什么ReactiveCocoa中推荐使用RACSignal来做信号处理而不是RACSubject

原文解释在这里http://cocoadocs.org/docsets/ReactiveCocoa/0.6.0/ 在标题Creating hot subscribables 底下

先贴原文:

The easiest way to create hot subscribables is by using RACSubject. Subjects are subscribables you can manually control with -sendNext:-sendError:-sendCompleted. Those will send the corresponding events to the subject's subscribers.

Remember that hot subscribables send events regardless of whether anyone's listening. Sometimes that's fine, but often we'd actually like to avoid missing any events.

Suppose that we're using RAC to interact with a web API. (In fact, that's exactly what the GHAPIDemo does.) We'd probably return a subject from our request method and the subject would send the value of the API call.

But there's a race condition here. If the API call sends its result and completes before I have a chance to subscribe, then I completely missed the whole point of the API call and I'd never know it.

Because of this, RAC has a few RACSubject subclasses:

  1. RACAsyncSubject. It doesn't send any value until it completes and if anyone subscribes after it has completed, it resends the last value it received to that new subscriber and tells the subscriber it's completed.
  2. RACReplaySubject. It remembers every value it sends (or some pre-defined cut-off you give it) and replays those to any subscriber that misses them.
  3. RACBehaviorSubject. It remembers the last value it received and sends that to any new subscribers that missed it.

注:Subject->发送者,Subscriber->订阅者,Signal->信号

     主要还是要看原文

原文的意思稍微翻译一下:

1、关于RACSubject:创建一个热订阅的最简单方法是用RACSubject, Subject(其本身是一个发送者,也就是它既能订阅又能发送信号)是可以用来主动控制sendNext:,sendError,sendCompleted,等操作的一个订阅者,它会将相同的事件发给订阅者。

2、热订阅传递事件的时候是会忽略所有的监听(造成监听实效了。)。有时候这种方式的消息传递不会造成影响,通常我们是希望规避一些风险操作以免造成事件丢失。

    举个例子:如果我们用RAC去处理一个web API的请求,我们可以从请求结果中返回一个subject对象,然后subject会将request中拿到的结果传递出来。这时候有一种情况是。如果API的send 和 。        complete 的方法在 传递信号之前,我们的的整个网络请求的结果就丢失了,并且我们还不会知道是因为这个丢失的。

 RACSubject 有3个子类RACAsyncSubjectRACReplaySubjectRACBehaviorSubject

RACAsyncSubject这个类定义的发送者会在它本身事件完成,或者它的下一步完成的时候把它接收到的最新的值传递给下一个订阅者。

RACReplaySubject: 这个类会记住它接收过的所有值,并且将这些值中的一些传递给那些对应的丢失值的订阅者。

RACBehaviorSubject:这个类会记住最后一个它接收到的值,并且将它发送给任意一个丢失过这个值的新的订阅者

原因在红色英文那段,具体的跟热订阅如何处理( 跟RACSubject字类的关系)有关吧