(整个关于ReactiveCocoa的工程可以在https://github.com/qianhongqiang/QHQReactive下载)
ReactiveCocoa的介绍我就不说了,可以自行百度。ReactiveCocoa这个框架目前来看很热门,但是不流行。归根到底,是学习成本太高,光看头文件,你几乎就根本不知道该如何使用。ReactiveCocoa内部实现大量使用了block,在block嵌套比较深的情况下,阅读源码也变得困难。我这里就给大家做个抽离,分解各个模块。因为我刚开始阅读时,我甚至于不知道该如何入手。源码解析如有错误,欢迎指正。
首先我先展示一段ReactiveCocoa的代码
```
RACSignal *signal = [RACSignal createSignal:^(id subscriber) {
[subscriber sendNext:[NSDate date]];
[subscriber sendCompleted];
return
nil;
}];
[signal subscribeNext:^(id x) {
NSLog(@
"next:%@"
, x);
} error:^(NSError *error) {
NSLog(@
"error:%@"
, error);
} completed:^{
NSLog(@
"completed"
);
}];
@interface QHQSignal ()
@property (nonatomic, copy) void (^didSubscriber)(id subscriber);
@property (nonatomic, strong) QHQSubscriber *scriber;
@end
@implementation QHQSignal
+(QHQSignal *)createSignal:(void (^)(id subscriber))didSubscriber {
QHQSignal *signal = [[self alloc] init];
signal.didSubscriber = didSubscriber;
return signal;
}
-(void)subscribeNext:(void (^)(id))nextBlock {
QHQSubscriber *scriber = [QHQSubscriber subscriberWithNextBlock:nextBlock];
self.scriber = scriber;
self.didSubscriber(self.scriber);
}
@end
@interface QHQSubscriber ()
@property (nonatomic, copy) void(^nextBlock)(id x);
@property (nonatomic, copy) void(^completionBlock)(id x);
@property (nonatomic, copy) void(^errorBlock)(id x);
@end
@implementation QHQSubscriber
+(instancetype)subscriberWithNextBlock:(void (^)(id x))nextBlock {
return [self subscriberWithNextBlock:nextBlock completionBlock:nil errorBlock:nil];
}
+(instancetype)subscriberWithNextBlock:(void (^)(id x))nextBlock completionBlock:(void (^)(id x))completionBlock errorBlock:(void (^)(id x))errorBlock {
QHQSubscriber *subscriber = [[QHQSubscriber alloc] init];
subscriber.nextBlock = nextBlock;
subscriber.completionBlock = completionBlock;
subscriber.errorBlock = errorBlock;
return subscriber;
}
-(void)sendNext:(id)next {
if (self.nextBlock) {
self.nextBlock(next);
}
}
@end
QHQSignal *demoSignal = [QHQSignal createSignal:^(id subscriber) {
[subscriber sendNext:@"1"];
}];
[demoSignal subscribeNext:^(id x) {
NSLog(@"%@",x);
}];