iOS DeveloperiOS 开发每天分享优质文章程序员

ReactiveCocoa 初识

2017-04-01  本文已影响84人  漂泊海上的大土豆

简单介绍:

ReactiveCocoa 是近年来比较黑科技的开源框架,但是学习路线比较陡峭,现在已经更新到5.0并已全面支持 Swift 语言,针对 objc 的部分已经独立分离出来,停留在了 pod 'ReactiveObjC','~> 2.1.2' 本次学习针对的是 objc 的部分。


Functional Reactive Programming

学习 ReactiveCocoa 就要提到下面这种编程思想 Functional Reactive Programming 函数式 响应式 编程思想。

例如:

a = 1
b = 2
c = a + b = 3

b = 3
// now what is the value of c?

我们期望在 b 的值变化后 c 的值也会随之变化,所以叫做响应式编程。在 iOS 中运用 KVC. KVO. NSNotification. Delegate 等也可以做到这样的事情,但往往不够直观也比较麻烦。

而 RAC 统一了对 KVO、UI Event、Network request、Async work 的处理,因为它们本质上都是值的变化(Values over time)。


ReactiveCocoa

ReactiveCocoa 整体围绕着 RACSignal 展开,也是它的核心,它其实是一个事件源,RACSignal 会给它的订阅者(subscribers)发送一连串的事件。有三种事件:nexterrorcompletedSignal 可以在 errorcompleted 事件发出前发出任意多的 next 事件。RACCommand RACObserve RACSubject 都是其中比较重要的类。

图片来自 Limboy 的技术博客,链接在本文底部

几个简单的小🌰

// When self.username changes, logs the new name to the console.
//
// RACObserve(self, username) creates a new RACSignal that sends the current
// value of self.username, then the new value whenever it changes.
// -subscribeNext: will execute the block whenever the signal sends a value.
[RACObserve(self, username) subscribeNext:^(NSString *newName) {
   NSLog(@"%@", newName);
}];

// 只有当名字以'j'开头,才会被记录
[[RACObserve(self, username)
    filter:^(NSString *newName) {// 过滤语法
        return [newName hasPrefix:@"j"];
    }]
    subscribeNext:^(NSString *newName) {
        NSLog(@"%@", newName);
    }];
// Logs a message whenever the button is pressed.
//
// RACCommand creates signals to represent UI actions. Each signal can
// represent a button press, for example, and have additional work associated
// with it.
//
// -rac_command is an addition to NSButton. The button will send itself on that
// command whenever it's pressed.
self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) {
    NSLog(@"button was pressed!");
    return [RACSignal empty];
}];
RAC(self.outputLabel, text) = self.inputTextField.rac_textSignal;

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读