響應(yīng)式編程之ReactiveObjC常見用法

ReactiveObjC是ReactiveCocoa系列的一個OC方面用得很多的響應(yīng)式編程三方框架,也就是大家經(jīng)常提到的RAC,也許大家對RAC還不是很了解,不知道這個框架用來干嘛,有什么好處,當(dāng)你看了以下demo后,你會發(fā)現(xiàn),RAC真的很強(qiáng)大,并且你會不知不覺的愛上它。

一、首先你要使用這個三方框架,必須先用pod導(dǎo)入這個框架。在podfile中添加下面這一句。

pod 'ReactiveObjC'

二、接下來我們來看看具體使用方式,讓你徹底感受一下它的魅力。

(1)代替監(jiān)聽事件方法(按鈕點(diǎn)擊)

-(void)demo1{
//創(chuàng)建一個按鈕
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 70, 70)];
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
btn.tag = 1001;
//監(jiān)聽點(diǎn)擊事件
[[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
    NSLog(@"按鈕點(diǎn)擊了%@",x);
}];
}

(2)代替KVO

-(void)demo2{
//創(chuàng)建一個按鈕
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 70, 70)];
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
//監(jiān)聽點(diǎn)擊事件
[[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
    //改變btn的Frame
    x.frame = CGRectMake(100,100,200, 200);
}];
[[btn rac_valuesAndChangesForKeyPath:@"frame" options:(NSKeyValueObservingOptionNew) observer:self] subscribeNext:^(RACTwoTuple<id,NSDictionary *> * _Nullable x) {
    //RACTwoTuple是一個集合類型,可以用數(shù)組的方式獲取到里面的內(nèi)容。
    NSLog(@"frame改變了%@",x.second);
}];
//這樣的KVO你可以覺得好像并沒有多了不起,那你看看demo3。
}

(3)代替代理,例如自定義view中的某個控件傳值到controller

新建一個自定義view——RACView,重寫初始化方法。

在RACView.h文件中定義一個rac信號屬性

@property (nonatomic,strong)RACSubject *btnClickSingle;

在.m文件中重寫初始化方法,發(fā)送信號

-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
    self.backgroundColor = [UIColor redColor];
    //創(chuàng)建一個按鈕
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 70, 70)];
    btn.backgroundColor = [UIColor redColor];
    [self addSubview:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //發(fā)送信號
        [self.btnClickSingle sendNext:@"按鈕點(diǎn)擊咯"];
        }];
    }
    return self;
}
-(RACSubject *)btnClickSingle{
    if (!_btnClickSingle) {
        _btnClickSingle = [RACSubject subject];
    }
    return _btnClickSingle;
}

在ViewController中

//只能代替沒有返回值的代理
-(void)demo3{
    RACView *racView = [[RACView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:racView];
    //替代了代理把值從racView中傳了過來。
    [racView.btnClickSingle subscribeNext:^(id  _Nullable x) {
        //要傳多個值,,可以傳一個集合
        NSLog(@"%@",x);
    }];
}

(4)簡化第三種代理傳值

同樣先自定義一個RACView,重寫初始化方法

-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
    self.backgroundColor = [UIColor redColor];
    //創(chuàng)建一個按鈕
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 70, 70)];
    btn.backgroundColor = [UIColor redColor];
    [self addSubview:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //發(fā)送信號
        [self sendValue:@"1234" andDic:@{@"key":@"value"}];//這句是demo4的

    }];
}
return self;
}

在.h文件中定義一個方法,不需要實(shí)現(xiàn)

//demo4用
-(void)sendValue:(NSString *)str andDic:(NSDictionary *)dic;

在ViewController中

-(void)demo4{
//監(jiān)聽指定的某個方法傳參
RACView *racView = [[RACView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)];
[self.view addSubview:racView];
[[racView rac_signalForSelector:@selector(sendValue:andDic:)] subscribeNext:^(RACTuple * _Nullable x) {
    //當(dāng)有多個參數(shù)傳遞時,傳遞過來的是集合,假如要取集合中某個元素的內(nèi)容,可以用一下方式
    NSLog(@"按鈕點(diǎn)擊了%@",x.first);
}];
}

(5)代替通知

-(void)demo5{
//創(chuàng)建一個文本輸入框
UITextField *field = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 200, 50)];
field.backgroundColor = [UIColor grayColor];
[self.view addSubview:field];

// 監(jiān)聽鍵盤彈出事件
[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:[self rac_willDeallocSignal]] subscribeNext:^(NSNotification * _Nullable x) {
    NSLog(@"%@", x);
}];
}

(6)監(jiān)聽文本輸入框文字的變化

-(void)demo6{
    //創(chuàng)建一個文本輸入框
    UITextField *field = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 200, 50)];
    field.backgroundColor = [UIColor grayColor];
    [self.view addSubview:field];
    [field.rac_textSignal subscribeNext:^(id x) {
        NSLog(@"文字改變了%@",x);
    }];
}

(7)代替timer循環(huán)執(zhí)行某個方法

-(void)demo7{
    [[RACSignal interval:1.0 onScheduler:[RACScheduler scheduler]] subscribeNext:^(NSDate * _Nullable x) {
        NSLog(@"%@",x);
    }];
}

(8)RAC代替timer實(shí)現(xiàn)登錄驗(yàn)證碼倒計時

-(void)demo8{
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(40, 70, 200, 50)];
    btn.titleLabel.textAlignment = NSTextAlignmentCenter;
    btn.backgroundColor = [UIColor greenColor];
    [btn setTitle:@"發(fā)送驗(yàn)證碼" forState:(UIControlStateNormal)];
    [self.view addSubview:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        self.time = 10;
        btn.enabled = NO;
        [btn setTitle:[NSString stringWithFormat:@"請稍等%d秒",_time] forState:UIControlStateDisabled];
        _disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
            //減去時間
            _time --;
            //設(shè)置文本
            NSString *text = (_time > 0) ? [NSString stringWithFormat:@"請稍等%d秒",_time] : @"重新發(fā)送";
            if (_time > 0) {
                btn.enabled = NO;
                [btn setTitle:text forState:UIControlStateDisabled];
            }else{
                btn.enabled = YES;
                [btn setTitle:text forState:UIControlStateNormal];
                //關(guān)掉信號
                [_disposable dispose];
            }
            
        }];
    }];
    
}

注意這個方法需要定義兩個屬性

@property (nonatomic,assign)int time;
@property (nonatomic,strong)RACDisposable *disposable;

(9)一個方法同時接受多個信號

-(void)demo9{
    // 處理多個請求,都返回結(jié)果的時候,統(tǒng)一做處理.
    RACSignal *request1 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        // 發(fā)送請求1
        [subscriber sendNext:@"發(fā)送請求1"];
        return nil;
    }];
    
    RACSignal *request2 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        // 發(fā)送請求2
        [subscriber sendNext:@"發(fā)送請求2"];
        return nil;
    }];
    
    // 使用注意:幾個信號,selector的方法就幾個參數(shù),每個參數(shù)對應(yīng)信號發(fā)出的數(shù)據(jù)。
    // 不需要訂閱:不需要主動訂閱,內(nèi)部會主動訂閱
    [self rac_liftSelector:@selector(updateUIWithR1:r2:) withSignalsFromArray:@[request1,request2]];
    
}
// 更新UI
- (void)updateUIWithR1:(id)data r2:(id)data1
{
    NSLog(@"更新UI%@ %@",data,data1);
}

二、ReactiveObjC中常用的宏

(1)RACObserve(就是一個宏定義):快速的監(jiān)聽某個對象的某個屬性改變

-(void)demo10{
    // 監(jiān)聽self.view的center屬性,當(dāng)center發(fā)生改變的時候就會觸發(fā)NSLog方法
    [RACObserve(self.view, center) subscribeNext:^(id x) {
        NSLog(@"%@", x);
    }];
}

(2)用來給某個對象的某個屬性綁定信號,只要產(chǎn)生信號內(nèi)容,就會把內(nèi)容給屬性賦值

-(void)demo11{
    //創(chuàng)建一個文本輸入框
    UITextField *field = [[UITextField alloc]initWithFrame:CGRectMake(50, 120, 200, 50)];
    field.backgroundColor = [UIColor grayColor];
    [self.view addSubview:field];
    //創(chuàng)建一個label
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 200, 50)];
    [self.view addSubview:label];
    //將輸入框內(nèi)容給label
    RAC(label,text) = field.rac_textSignal;
}

(3)登錄按鈕的狀態(tài)根據(jù)賬號和密碼輸入框內(nèi)容的長度來改變

-(void)demo12{
    UITextField *userNameTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 70, 200, 50)];
    UITextField *passwordTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 130, 200, 50)];
    userNameTF.placeholder = @"請輸入用戶名";
    passwordTF.placeholder = @"請輸入密碼";
    [self.view addSubview:userNameTF];
    [self.view addSubview:passwordTF];
    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(40, 180, 200, 50)];
    [loginBtn setTitle:@"馬上登錄" forState:UIControlStateNormal];
    [self.view addSubview:loginBtn];
    //根據(jù)textfield的內(nèi)容來改變登錄按鈕的點(diǎn)擊可否
    RAC(loginBtn, enabled) = [RACSignal combineLatest:@[userNameTF.rac_textSignal, passwordTF.rac_textSignal] reduce:^id _Nullable(NSString * username, NSString * password){
        return @(username.length >= 11 && password.length >= 6);
    }];
    //根據(jù)textfield的內(nèi)容來改變登錄按鈕的背景色
    RAC(loginBtn, backgroundColor) = [RACSignal combineLatest:@[userNameTF.rac_textSignal, passwordTF.rac_textSignal] reduce:^id _Nullable(NSString * username, NSString * password){
        return (username.length >= 11 && password.length >= 6) ? [UIColor redColor] : [UIColor grayColor];
    }];
    
}

(4)避免循環(huán)引用,外部@weakify(self),內(nèi)部@strongify(self)

-(void)demo13{
    // @weakify() 宏定義
    @weakify(self) //相當(dāng)于__weak typeof(self) weakSelf = self;
    RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self)  //相當(dāng)于__strong typeof(weakSelf) strongSelf = weakSelf;
        NSLog(@"%@",self.view);
        return nil;
    }];
    _signal = signal;
}

三、總結(jié):

RAC的操作類似于iOS中系統(tǒng)的通知,整個流程就三個步驟,初始化信號,訂閱信號,發(fā)送信號。只是框架本身許多方法隱藏了其中的一步或者兩步,在框架內(nèi)部實(shí)現(xiàn)了,所以我們用起來會很順手。RAC為事件提供了很多處理方法,而且利用RAC處理事件很方便,可以把要處理的事情,和監(jiān)聽的事情的代碼放在一起——以Block的方式,這樣非常方便我們管理,就不需要跳到對應(yīng)的方法里。

四、最后為大家提供demo下載地址,可能更方便你學(xué)習(xí)理解。

github下載地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容