iOS响应式编程学习ReactiveCocoa-1

转载请注明出处,谢谢

受到响应式编程的启发,然后有了ReactiveCocoa,它可以避免在某些地方去修改或者替换一些变量的值。
RAC提供了signal(信号),用来捕捉当前或者将来的变量值。

通过对信号的chaining(链接),combining(组合),以及反射(reacting), 代码可以声明形式的,不需要持续的去监听和更新变量值。

例如:
UITextField可以利用signal绑定到最近的时刻,即使它改变,不用额外的代码去监听,并及时更新textfield的某些属性。 这个机制很像KVO, 只需要在重写的Block操作即可。

信号同样可以表示异步的操作符,就像期望和承诺,这个极大的简化了处理异步机制和网络机制的逻辑。

eg: 当self.username 改变, 会在控制台中输出新的名字:
RACObserve(self, username)产生了一个新的RACSignal,它传递self.username的当前的值,然后新的值无论怎么改变,-subscribeNext: 每当发送一个新的值得时候,都会执行block块

// 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: 
[RACObserve(self, username) subscribeNext:^(NSString *newName) {
    NSLog(@"%@", newName);
}];

但是这个不同于KVO 通知,signals信号之间可以被链接到一起,然后再操作:
-filter:  只有当Block返回的值是YES的时候,才会返回一个新的RACSignal

//只有以j字母打头的名字才会被输出
// Only logs names that starts with "j".
//
// -filter returns a new RACSignal that only sends a new value when its block
// returns YES.
[[RACObserve(self, username)
    filter:^(NSString *newName) {
        return [newName hasPrefix:@"j"];
    }]
    subscribeNext:^(NSString *newName) {
        NSLog(@"%@", newName);
  }];

信号同样被用来获得某些状态,而不需要去监听某些属性和去设置其它的属性去响应新的值。
RAC通过一些信号(signals)和操作符(operations)去传递(代表)一些属性的值。

+combineLatest: 携带一个信号数组(array of signals), 每当其中某个信号改变时,都会通过最新的值去执行block块
// Creates a one-way binding so that self.createEnabled will be
// true whenever self.password and self.passwordConfirmation
// are equal.
//
// RAC() is a macro that makes the binding look nicer.
// 
// +combineLatest:reduce: takes an array of signals, executes the block with the
// latest value from each signal whenever any of them changes, and returns a new
// RACSignal that sends the return value of that block as values.
RAC(self, createEnabled) = [RACSignal 
    combineLatest:@[ RACObserve(self, password), RACObserve(self, passwordConfirmation) ] 
    reduce:^(NSString *password, NSString *passwordConfirm) {
        return @([passwordConfirm isEqualToString:password]);
    }];

signals 可以建立在随着时间的任何值,eg:它们可以代表按钮的点击

RACCommand建立signals 去表示一写动作(actions), 每个信号可以代表一个按钮的点击,并且其它有关的行为、
-rac_command: 它是button的一个扩展(category),  当它被点击的时候,这个button将会将它自己传递过去
// 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];
}];

异步的网络操作
//将Log in 按钮和基于网络登录的动作连接起来
//当Login Command 执行之后,Block将会执行,并开始Login 进程

// Hooks up a "Log in" button to log in over the network.
//
// This block will be run whenever the login command is executed, starting
// the login process.
self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^(id sender) {
    // The hypothetical -logIn method returns a signal that sends a value when
    // the network request finishes.
    return [client logIn];
}];

//-executionSignals : 在上面loginCommand每次执行的时候, executionSignals都会返回,它包含有上面的signals
// -executionSignals returns a signal that includes the signals returned from
// the above block, one for each time the command is executed.
[self.loginCommand.executionSignals subscribeNext:^(RACSignal *loginSignal) {
    // Log a message whenever we log in successfully.
    [loginSignal subscribeCompleted:^{
        NSLog(@"Logged in successfully!");
    }];
}];

// Executes the login command when the button is pressed.
self.loginButton.rac_command = self.loginCommand;

//Signals 同样可以代表timers或者UI 事件, 或者其它任何随着事件改编的东东。
通过signals的异步操作,例如对信号的链接,转换, 可以构建出复杂的行为。
在一系列操作完成之后,事件可以简单的被触发~
Signals can also represent timers, other UI events, or anything else that changes over time.
Using signals for asynchronous operations makes it possible to build up more complex behavior by chaining and transforming those signals. Work can easily be triggered after a group of operations completes:

//执行2个网络操作,并且在两个操作都完成的时候,在控制台输出信息
+merge:携带一组信号(signals), 并且在所有的signal 完成的时候,通过值传递返回一个新的RACSignal
-subscribeCompleted:在该signal完成的时候将会执行block块
// Performs 2 network operations and logs a message to the console when they are
// both completed.
//
// +merge: takes an array of signals and returns a new RACSignal that passes
// through the values of all of the signals and completes when all of the
// signals complete.
//
// -subscribeCompleted: will execute the block when the signal completes.
[[RACSignal 
    merge:@[ [client fetchUserRepos], [client fetchOrgRepos] ]] 
    subscribeCompleted:^{
        NSLog(@"They're both done!");
    }];

//signals 可以被线性的链接起来去执行一个异步的操作,从而避免使用Block回调,这个类似于 futures and promises中经常常提到的
Signals can be chained to sequentially execute asynchronous operations, instead of nesting callbacks with blocks. This is similar to how  futures and promises  are usually used:

//前提:-loginUser 方法在登录完成之后会返回一个signal
//用户登录后, 载入当前缓存的消息,然后从服务器请求剩余的信息,当都完成之后,在控制台输出一个message
-flattenMap: 
// Logs in the user, then loads any cached messages, then fetches the remaining
// messages from the server. After that's all done, logs a message to the
// console.
//
// The hypothetical -logInUser methods returns a signal that completes after
// logging in.
//
// -flattenMap: will execute its block whenever the signal sends a value, and
// returns a new RACSignal that merges all of the signals returned from the block
// into a single signal.
[[[[client 
    logInUser] 
    flattenMap:^(User *user) {
        // Return a signal that loads cached messages for the user.
        return [client loadCachedMessagesForUser:user];
    }]
    flattenMap:^(NSArray *messages) {
        // Return a signal that fetches any remaining messages.
        return [client fetchMessagesAfterMessage:messages.lastObject];
    }]
    subscribeNext:^(NSArray *newMessages) {
        NSLog(@"New messages: %@", newMessages);
    } completed:^{
        NSLog(@"Fetched all messages.");
    }];

//RAC 可以很容易的将一个异步操作的结果和某个东东绑定起来
RAC even makes it easy to bind to the result of an asynchronous operation:

//这里self.imageView将会setImage ,在user’s avator一完成下载的时候。
//前提: -fetchUserWithUsername method 在sends the user的时候返回一个signal
//-deliverOn: 建立一个新的signal,并将会其它queues执行它们的work。
//在这个例子当中, 先到后台工作,然后返回到主线程。

// Creates a one-way binding so that self.imageView.image will be set the user's
// avatar as soon as it's downloaded.
//
// The hypothetical -fetchUserWithUsername: method returns a signal which sends
// the user.
//
// -deliverOn: creates new signals that will do their work on other queues. In
// this example, it's used to move work to a background queue and then back to the main thread.
//
// -map: calls its block with each user that's fetched and returns a new
// RACSignal that sends values returned from the block.
RAC(self.imageView, image) = [[[[client 
    fetchUserWithUsername:@"joshaber"]
    deliverOn:[RACScheduler scheduler]]
    map:^(User *user) {
        // Download the avatar (this is done on a background queue).
        return [[NSImage alloc] initWithContentsOfURL:user.avatarURL];
    }]
    // Now the assignment will be done on the main thread.
    deliverOn:RACScheduler.mainThreadScheduler];


表达的不好的地方还请谅解,初学RAC,有错误的地方还请指出,欢迎留言...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值