ReactiveCocoa 冷热信号

96
漂泊海上的大土豆
2017.04.05 15:42* 字数 1051

官方的英文描述:

Cold signal is sequences that are passive and start producing notifications on request (when subscribed to), and hot signal is sequences that are active and produce notifications regardless of subscriptions.

理解下来就是:

1.Hot Observable 是主动的,尽管你并没有订阅事件,但是它会时刻推送;而 Cold Observable是被动的,只有当你订阅的时候,它才会发布消息。
2.Hot Observable 可以有多个订阅者,是一对多,集合可以与订阅者共享信息;而 Cold Observable 只能一对一,当有不同的订阅者,消息是重新完整发送。


热信号 RACSubject

RAC 的世界中,所有的热信号都属于一个类 —— RACSubject

A subject, represented by the RACSubject class, is a signal that can be manually controlled.

Subjects can be thought of as the “mutable” variant of a signal, much like NSMutableArray is for NSArray. They are extremely useful for bridging non-RAC code into the world of signals.

For example, instead of handling application logic in block callbacks, the blocks can simply send events to a shared subject instead. The subject can then be returned as a RACSignal, hiding the implementation detail of the callbacks.

Some subjects offer additional behaviors as well. In particular, RACReplaySubject can be used to buffer events for future subscribers, like when a network request finishes before anything is ready to handle the result.

从这段描述中,我们可以发现Subject具备如下三个特点:

  • Subject 是“可变”的。
  • Subject 是非 RACRAC 的一个桥梁。
  • Subject 可以附加行为,例如 RACReplaySubject 具备为未来订阅者缓冲事件的能力。

创建方式:

+ (instancetype)subject;

🌰

RACSubject *subject = [RACSubject subject];

// Subscriber 1
[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"1st Sub: %@", x);
}];
[subject sendNext:@1];

// Subscriber 2
[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"2nd Sub: %@", x);
}];
[subject sendNext:@2];

// Subscriber 3
[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"3rd Sub: %@", x);
}];
[subject sendNext:@3];
[subject sendCompleted];

打印:

2017-04-05 11:17:43.901 simpleRacDemo[2985:162129] 1st Sub: 1
2017-04-05 11:17:43.901 simpleRacDemo[2985:162129] 1st Sub: 2
2017-04-05 11:17:43.901 simpleRacDemo[2985:162129] 2nd Sub: 2
2017-04-05 11:17:43.902 simpleRacDemo[2985:162129] 1st Sub: 3
2017-04-05 11:17:43.902 simpleRacDemo[2985:162129] 2nd Sub: 3
2017-04-05 11:17:43.902 simpleRacDemo[2985:162129] 3rd Sub: 3

显然,RACSubject 是时间相关的,它在发送消息时只会向已订阅的订阅者推送消息。也就是说订阅者无法收到订阅前已经发出的消息。

RACSubject 有两个子类 RACBehaviorSubjectRACReplaySubject 前者在订阅时会向订阅者发送最新的消息,后者在订阅之后可以重新发送之前的所有消息序列。

RACBehaviorSubject 🌰

RACBehaviorSubject *subject = [RACBehaviorSubject subject];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"1st Sub: %@", x);
}];
[subject sendNext:@1];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"2nd Sub: %@", x);
}];
[subject sendNext:@2];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"3rd Sub: %@", x);
}];
[subject sendNext:@3];
[subject sendCompleted];

打印:

2017-04-05 11:26:35.422 simpleRacDemo[3033:190530] 1st Sub: (null)
2017-04-05 11:26:35.422 simpleRacDemo[3033:190530] 1st Sub: 1
2017-04-05 11:26:35.422 simpleRacDemo[3033:190530] 2nd Sub: 1
2017-04-05 11:26:35.422 simpleRacDemo[3033:190530] 1st Sub: 2
2017-04-05 11:26:35.422 simpleRacDemo[3033:190530] 2nd Sub: 2
2017-04-05 11:26:35.423 simpleRacDemo[3033:190530] 3rd Sub: 2
2017-04-05 11:26:35.423 simpleRacDemo[3033:190530] 1st Sub: 3
2017-04-05 11:26:35.423 simpleRacDemo[3033:190530] 2nd Sub: 3
2017-04-05 11:26:35.423 simpleRacDemo[3033:190530] 3rd Sub: 3

在每次订阅者订阅 RACBehaviorSubject 之后,都会向该订阅者发送当前最新的消息。

RACBehaviorSubject 有一个用于创建包含默认值的类方法 +behaviorSubjectWithDefaultValue:,如果将上面的第一行代码改成:

RACBehaviorSubject *subject = [RACBehaviorSubject behaviorSubjectWithDefaultValue:@0]; 

那么在第一个订阅者刚订阅 RACBehaviorSubject 时就会收到 @0 对象。

RACReplaySubject 🌰

RACReplaySubject 相当于一个自带 bufferRACBehaviorSubject,它可以在每次有新的订阅者订阅之后发送之前的全部消息。

RACReplaySubject *subject = [RACReplaySubject subject];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"1st Subscriber: %@", x);
}];
[subject sendNext:@1];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"2nd Subscriber: %@", x);
}];
[subject sendNext:@2];

[subject subscribeNext:^(id  _Nullable x) {
    NSLog(@"3rd Subscriber: %@", x);
}];
[subject sendNext:@3];
[subject sendCompleted];

打印:

2017-04-05 11:37:46.370 simpleRacDemo[3109:254111] 1st Subscriber: 1
2017-04-05 11:37:46.370 simpleRacDemo[3109:254111] 2nd Subscriber: 1
2017-04-05 11:37:46.370 simpleRacDemo[3109:254111] 1st Subscriber: 2
2017-04-05 11:37:46.370 simpleRacDemo[3109:254111] 2nd Subscriber: 2
2017-04-05 11:37:46.371 simpleRacDemo[3109:254111] 3rd Subscriber: 1
2017-04-05 11:37:46.371 simpleRacDemo[3109:254111] 3rd Subscriber: 2
2017-04-05 11:37:46.371 simpleRacDemo[3109:254111] 1st Subscriber: 3
2017-04-05 11:37:46.371 simpleRacDemo[3109:254111] 2nd Subscriber: 3
2017-04-05 11:37:46.371 simpleRacDemo[3109:254111] 3rd Subscriber: 3

所有订阅 RACReplaySubject 的对象都能获得完整的序列。

Tips:

RACSubject 的实现并不复杂,只是存储了一个遵循 RACSubscriber 协议的对象列表以及所有的消息,但是在解决实际问题时却能够很好地解决很多与网络操作相关的问题。


冷信号 RACSignal

这里举一个冷信号的简单🌰

 RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendNext:@1];
        [subscriber sendNext:@2];
        [subscriber sendNext:@3];
        [subscriber sendCompleted];
        return nil;
    }];
    NSLog(@"Signal was created.");
    [[RACScheduler mainThreadScheduler] afterDelay:0.1 schedule:^{
        [signal subscribeNext:^(id x) {
            NSLog(@"Subscriber 1 recveive: %@", x);
        }];
    }];

    [[RACScheduler mainThreadScheduler] afterDelay:1 schedule:^{
        [signal subscribeNext:^(id x) {
            NSLog(@"Subscriber 2 recveive: %@", x);
        }];
    }];

打印:

2017-04-05 10:52:37.678 simpleRacDemo[2882:50996] Signal was created.
2017-04-05 10:52:37.784 simpleRacDemo[2882:50996] Subscriber 1 recveive: 1
2017-04-05 10:52:37.785 simpleRacDemo[2882:50996] Subscriber 1 recveive: 2
2017-04-05 10:52:37.785 simpleRacDemo[2882:50996] Subscriber 1 recveive: 3
2017-04-05 10:52:38.776 simpleRacDemo[2882:50996] Subscriber 2 recveive: 1
2017-04-05 10:52:38.776 simpleRacDemo[2882:50996] Subscriber 2 recveive: 2
2017-04-05 10:52:38.776 simpleRacDemo[2882:50996] Subscriber 2 recveive: 3

可以显而易见地看到,signal 的这个信号,在两个不同时间段的订阅过程中,分别完整地发送了所有的消息。


为什么要区分冷热信号?

在我们日常开发中,大多数情况是要产生副作用的,objc 本身也并不是纯函数语言。移动开发有很多页面与数据的交互,丰富的变化,也可以说我们是期待副作用的。

但是单纯的冷信号有时候会产生严重的问题,比如:

    //--------------------------------------------------------------------------------------------
    // 下面代码存在一个非常严重的问题
    // 每一次在 RACSignal 上执行 -subscribeNext: 以及类似方法时,都会发起一次新的网络请求,我们希望避免这种情况的发生。
    // RACSignal                   一对一的单向数据流
    // RACMulticastConnection      一对多的单向数据流
    // RACChannel                  一对一的双向数据流
    //--------------------------------------------------------------------------------------------
    RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        NSURL *url = [NSURL URLWithString:@"http://localhost:3000"];
        
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
        NSString *URLString = [NSString stringWithFormat:@"/api/products/1"];
        NSURLSessionDataTask *task = [manager GET:URLString
                                       parameters:nil
                                         progress:nil
                                          success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                                              [subscriber sendNext:responseObject];
                                              [subscriber sendCompleted];
                                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                              [subscriber sendError:error];
                                          }];
        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];
    }];
    
    [requestSignal subscribeNext:^(id  _Nullable x) {
        NSLog(@"product: %@", x);
    }];
    
    [requestSignal subscribeNext:^(id  _Nullable x) {
        NSNumber *productId = [x objectForKey:@"id"];
        NSLog(@"productId: %@", productId);
    }];
    
    //--------------------------------------------------------------------------------------------

每一次订阅都会触发一次网络请求,这显然不是我们期望的。

此时可以使用 RACCommand 它并不表示数据流,只是一个继承自 NSObject 的类,但是它却可以用来创建和订阅用于响应某些事件的信号,是一个用于管理 RACSignal 的创建与订阅的类。

关于如何利用 RACCommand 封装简单的网络请求可以参考我的这篇文章。

利用 RAC 封装网络请求 - 简书


参考资料:

iOS开发笔记