IOS RAC exploration (usage)

Time:2022-1-9

introduce

1.ReactiveObjC github
2.ReactiveObjC(officially known asReactiveCocoaorRAC)It’s aObjective-CFramework, using the programming idea of function + response.
3.RACEverything inside is a signal, which encapsulates KVO, agent, notification, tag ERT and timer. Yes, our code looks more compact. It is also more convenient to use
4. Due to the poor readability of Rac, it may cost some people who are not familiar with it to learn, so team collaborative development needs to be carefully considered when using it.
5. This article only introduces the usage scenario of Rac, and does not make an in-depth study on the implementation principle

Usage scenario

Import first#import <ReactiveObjC.h>

notice

1. In the past, after we wrote the registration notice, we also needed to write an acceptance method anddelloc removeObserverInside, but useRACAfter that, you only need one line of code to do it

//Notice
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil]subscribeNext:^(NSNotification * _Nullable x) {
            Nslog (@ "keyboard information:% @", x.userinfo);
    }];

KVO

In the past, when we listened to properties, we might need to call three methods, and the methods are very scattered

[self.name addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
}

- (void)dealloc{
    [self removeObserver:self forKeyPath:@"name"];
}

After using RAC

[RACObserve(self, name) subscribeNext:^(id  _Nullable x) {
        
    }];
    perhaps
    [[self.name rac_valuesForKeyPath:@"name" observer:self] subscribeNext:^(id  _Nullable x) {
    
    }];

agent

self.textField.delegate = self;
    [[self rac_signalForSelector:@selector(textFieldDidBeginEditing:) fromProtocol:@protocol(UITextFieldDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
  //Ractuple can get parameters
   UITextField *txt = (UITextField *)x.first;
       
    }];

taget (UI)

//UIButton
    [[self.button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
    }];
  
    [[self.textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        UITextField *txt = (UITextField *)x;
        NSLog(@"%@",txt.text);
    }];

Recommended Today

Try “clean architecture” in golang

Architecture is a philosophical problem and complex. I have just stepped into a finger. If there is anything wrong, thank you for your advice. What is “clean architecture”? “Clean architecture” is Robert C. Martin (Uncle Bob)(About,Robert C. Martin (16))Summarize the existing system architecture and put forward a concept in 2012. stayIn the text, his clean […]