我用RAC干了些什么(一)

对象间的交互, 主要有 target-actionNotificationKVODelegate

target-action

1
2
3
4
[[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *btn) {
// btn, 即 self.loginBtn
// 这里执行点击之后的操作
}];

可以用 BlocksKit 替代

KVO

1
2
3
4
[RACObserve(self, name) subscribeNext:^(NSString *name) {
// name 即 self.name
// 一旦 name 属性改变就立即进入到这个 block
}];
1
2
// self.myLab.text 随着 self.myTF.text 的改变而改变
RAC(self.myLab, text) = self.myTF.rac_textSignal;

Notificaiton

1
2
3
4
5
6
7
[[[[NSNotificationCenter defaultCenter]
rac_addObserverForName:UIKeyboardWillChangeFrameNotification object:nil]
// 这句不可少,表示 当 self 将要 dealloc 的时候,就要释放 通知
takeUntil:self.rac_willDeallocSignal]
subscribeNext:^(NSNotification *notification) {
NSLog(@"-----%@", notification.description);
}];

不要忘了还是原来的方法发送通知。

通知已经通过 RAC 内部得到了释放,所以不需要额外在 - dealloc 添加移除的代码

RACCommand

A command, represented by the RACCommand class, creates and subscribes to a signal in response to some action. This makes it easy to perform side-effecting work as the user interacts with the app.

简单的使用RACCommand 实现一个 viewModel 的网络请求。

每个viewModel都有不同的事件

ViewModel 持有一个 RACCommand 的属性 sourceCommand

初始化

1
2
3
4
5
6
7
8
9
10
// 直接构建
- (id)initWithSignalBlock:(RACSignal * (^)(id input))signalBlock;
// 只有当enabledSignal为true时, command才执行
- (id)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal * (^)(id input))signalBlock;
_sourceCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
return [[SYHTTPManager shared] request:[[SFAPI_Find_SectionList alloc] init]];
}];

订阅

失败和成功不能像订阅其他signal一样直接NextonError就可以。RACCommand 的失败消息, 都被分发到了 errors 这个属性。所以需要在这个地方订阅失败的消息.

1
2
3
4
5
6
7
8
// 订阅成功
[_sourceCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
PSLog(@"---%@",x);
}];
// 订阅失败
[_sourceCommand.errors subscribeNext:^(id x) {
PSLog(@"xxx%@",x);
}];

执行

1
[command execute:someParameters];
CepheusSun wechat
订阅我的公众号,每次更新我都不一定会告诉你!
坚持原创技术分享,您的支持将鼓励我继续创作!
0%