RAC 的核心思想:創(chuàng)建信號 - 訂閱信號 - 發(fā)送信號 ,并且在 RAC 中我們會看到大量的 block
RACObserve用法
@interface ViewController ()
/** */
@property (nonatomic, copy) NSString *username;
/** */
@property (nonatomic, copy) NSString *password;
/** */
@property (nonatomic, copy) NSString *content;
@end
------------------------------------------------------
// 監(jiān)聽self這個對象里面的一個username屬性
[RACObserve(self, username) subscribeNext:^(id _Nullable x) {
NSLog(@"%@", x);
}];
// 因為接受過來的是NSString則可以這樣寫
[RACObserve(self, username) subscribeNext:^(NSString *string) {
NSLog(@"%@", string);
}];
// 帶有過濾效果
[[RACObserve(self, username) filter:^BOOL(NSString *string) {
// 根據(jù)條件是否發(fā)送出值
return [string containsString:@"aa"];
}] subscribeNext:^(id _Nullable x) {
NSLog(@"%@", x);
}];
// RAC() 宏可以使得綁定表示的更清楚
// combineLatest填入多個監(jiān)聽 reduce根據(jù)數(shù)組順序 返回監(jiān)聽到的內(nèi)容
// 返回的值會被設(shè)置到RAC中的content中
RAC(self, content) = [RACSignal combineLatest:@[RACObserve(self, username), RACObserve(self, password)] reduce:^(NSString *name, NSString *pass){
return [NSString stringWithFormat:@"%@%@", name, pass];
}];
/* 監(jiān)聽 TextField 的輸入(內(nèi)容改變就會調(diào)用) */
[[textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"輸入框內(nèi)容:%@", x);
}];
/* 添加監(jiān)聽條件 */
[[textField.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
return value.length > 5; // 表示輸入文字長度 > 5 時才會調(diào)用下面的 block
}] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"輸入框內(nèi)容:%@", x);
}];
// 按鈕的監(jiān)聽事件
[[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"%@ 按鈕被點擊了", x); // x 是 button 按鈕對象
}];
// RAC接受返回值給loginButton對象的enabled屬性賦值
RAC(_loginButton, enabled) = [RACSignal combineLatest:@[_username.rac_textSignal, _password.rac_textSignal] reduce:^id _Nullable(NSString * username, NSString * password){
return @(username.length && password.length);
}];
// 替代通知 我們可以省去在dealloc中清除通知
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
NSLog(@"%@ 鍵盤彈起", x); // x 是通知對象
}];
// 當前類中的btnClick方法執(zhí)行了,就會有回調(diào)
[[self rac_signalForSelector:@selector(btnClick)] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@" view 中的按鈕被點擊了");
}];
// 監(jiān)聽屬性改變
[[button rac_valuesForKeyPath:@"frame" observer:self] subscribeNext:^(id _Nullable x) {
NSLog(@"屬性的改變:%@", x); // x 是監(jiān)聽屬性的改變結(jié)果
}];
// 監(jiān)聽屬性改變 另一種寫法
[RACObserve(button, frame) subscribeNext:^(id _Nullable x) {
NSLog(@"屬性的改變:%@", x); // x 是監(jiān)聽屬性的改變結(jié)果
}];
// 定時器功能 3秒后執(zhí)行一次
[[RACScheduler mainThreadScheduler]afterDelay:3 schedule:^{
NSLog(@"3秒后執(zhí)行一次");
}];
// 定時器 每隔兩秒執(zhí)行一次
// 這里要加takeUntil條件限制一下否則當控制器pop后依舊會執(zhí)行
[[[RACSignal interval:2 onScheduler:[RACScheduler mainThreadScheduler]] takeUntil:self.rac_willDeallocSignal ] subscribeNext:^(id x) {
NSLog(@"每兩秒執(zhí)行一次");
}];