I. Examples:

1. Create a signal:

RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { Block is called whenever a subscriber subscribes to a signal. // Send a signal [subscriber sendNext:@"ws"]; // If the data is not sent, it is better to send the signal to complete, internal will automatically call [RACDisposable disposable] unsubscribe signal. [subscriber sendCompleted]; // Cancel the signal, if the signal wants to be canceled, it must return a RACDisposable when the signal was canceled: 1. Automatic cancellation, which automatically unsubscribes when a signal's subscriber is destroyed, 2. Manually cancel, // when block is called: once a signal is unsubscribed // Block is used: to empty some resources when the signal is unsubscribedreturn[RACDisposable disposableWithBlock:^{// Block call time: When the signal has been sent to completion or error, this block will be automatically executed, unsubscribes the signal"Unsubscribe");  
        }];  
    }];  
Copy the code

2. Subscribe to signals

RACDisposable * Disposable = [signal] RACDisposable * Disposable = [signal // Block call time: Block. NSLog(@) is called whenever a signal sends data"Received data :%@",x); }]; // Unsubscribe [disposable dispose];Copy the code

This makes for a simple use of RAC. The sender sends “data” that will be received by the receiver’s subscribeNext. From this example, you might think of “asynchronous” and “observer mode.” Yes, these are all things RAC does and makes them simpler and cleaner. Everything in RAC will revolve around two points: one is the signal source and one is the subscriber. Isn’t that easy to understand? If you understand this or you already know that RAC is what it is, then congratulations, you have one foot in the RAC door, if not !!!! That doesn’t matter, keep reading…

Second, the role of ReactiveCocoa, that is, in what scenario

In our iOS development process, we often respond to events to handle certain business logic, such as button clicks, pulled-out refreshes, network requests, property changes (KVO), or user location changes (via CoreLocation). But these events are handled in different ways, such as Action, delegate, KVO, callback, and so on.

All of the above events can be handled by RAC. RAC provides many methods for handling events, and it is very convenient to use RAC to handle events, and listen to the event code together, which is very convenient for us to manage, there is no need to jump to the corresponding method. With RAC, you don’t need to worry about the order of calls, you just think about the result, and you write each operation in a series of nested methods, which is very much in line with our high aggregation, low coupling philosophy in development.

Three, each programming ideas under the comparison of the difference between a comparison:

3.1 Process oriented: Process is the core of dealing with things, step by step implementation.

3.2 Object-oriented: Everything is an object

3.3 Chain programming idea: multiple operations (lines of code) through the dot (.) Links together to form a single line of code, making the code readable. a(1).b(2).c(3)

  • Chain programming featuresBlock must have a return value (its own object) and a block argument (the value to operate on).
  • On behalf of: navigation framework.

3.4 Responsive programming idea: do not need to consider the order of call, just need to know the results, similar to the butterfly effect, produce an event, will affect many things, these events like flow out, and then affect the results, to borrow a word oriented to the object, everything is a flow.

  • On behalf of: KVO application.

3.5 Idea of functional programming: Operations are written as a series of nested function or method calls as far as possible.

  • Functional programming features: Each method must have a return value (its own object), take a function or a Block as an argument, Block argument (the value of the operation) Block return value (the result of the operation)

  • Representative: ReactiveCocoa.

ReactiveCocoa combines two programming styles:

Functional Programming

Reactive Programming

Therefore, RAC is described as a functional Responsive programming (FRP) framework.

Common usage in RAC development
Proxy: rac_signalForSelector: Used to replace the proxy. KVO: rac_valuesAndChangesForKeyPath: listens for an object property change. Rac_signalForControlEvents: Used to listen for an event. In lieu of notifications: rac_addObserverForName: Used to listen for a notification. Rac_textSignal: This signal is sent whenever the textbox changes. Processing when interface request for several times, need to take to the data, can display interface rac_liftSelector: withSignalsFromArray: Signals: when the incoming Signals (array) signal, each signal sendNext at least once, It's going to fire that first selector method.Copy the code

To view additional methods and modifiers, go to RAC Section Methods and Modifiers.

Specific code:
#pragma mark --textField property changes/ * * * * * * * * * * * * * * * * * create textField * * * * * * * * * * * * * * * * * * * / - (void) textFieldChange {/ / initializes a textField control UITextField at * textField = [[UITextField alloc] init]; textField.backgroundColor = [UIColor yellowColor]; textField.delegate = self ; [self.view addSubview:textField]; @weakify(self); [textField mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self);  make.size.mas_equalTo(CGSizeMake(180, 40)); make.center.equalTo(self.view); }]; / * * * * * * * * * * * * * * * * * listening textField changes the properties of the * * * * * * * * * * * * * * * * * * * / / / RAC internal wrapper class / / the default execution, so there will be a print, reason: please see the bottom of the RACbind// Listen for text changes in the textbox, and get the changed value whenever the textField changes. [textField. Rac_textSignal subscribeNext:^(id x) {// Get textField value}]; }#pragma mark -- Button uses to listen for events
-(void)textBtn  
{  
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];  
    [button setTitle:@"Click" forState:UIControlStateNormal]; button.backgroundColor = [UIColor redColor]; [self.view addSubview:button]; @weakify(self); [button mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self);  make.size.mas_equalTo(CGSizeMake(self.view.bounds.size.width, 30)); make.bottom.equalTo(self.view).offset(0); }]; // Convert the button click event into a signal, click the button, It will send signal [[button rac_signalForControlEvents: UIControlEventTouchUpInside] subscribeNext: ^ (id) x {/ / call RACViewController click  *VC = [[RACViewController alloc] init]; @strongify(self); [self presentViewController:VC animated:YES completion:^{ }]; }]; }#pragma Mark -- Gestures- (void) addTap {/ * * * * * * * * * * * * * * gesture to * * * * * * * * * * * * * * * * * / self. The userInteractionEnabled = YES; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init]; [[tap rac_gestureSignal] subscribeNext:^(id x) {// gesture trigger call}]; [self.view addGestureRecognizer:tap]; }#pragma mark -- Notification center- (void) notifiCenter {/ * * * * * * * * * * * * * * notice * * * * * * * * * * * * * * * * * / [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(id x) { }]; }#pragma mark -- Proxy
-(void)delegateDemo  
{  
    UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"RAC" message:@"ReactiveCocoa" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ensure", nil nil]; / / method one: agent / / [[self rac_signalForSelector: @ the selector (alertView: clickedButtonAtIndex:) fromProtocol:@protocol(UIAlertViewDelegate)] subscribeNext:^(id x) { // RACTuple *tuple = (RACTuple *)x ; / / tuples similar to the swift, / / / / NSLog (a tuple); / / / / NSLog (tuple. First); / / NSLog (tuple. Second); / / NSLog (tuple. Third); / / / /}]; [alterView show]; [[alterView rac_buttonClickedSignal] subscribeNext:^(id x) {}]; }#pragma mark -- KVO  -(void)addKvo { UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.delegate = (id<UIScrollViewDelegate>)self ; [self.view addSubview:scrollView]; UIView *scrollViewContentView = [[UIView alloc] init]; scrollViewContentView.backgroundColor = [UIColor yellowColor]; [scrollView addSubview:scrollViewContentView]; @weakify(self); [scrollView mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self);  make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(80, 80, 80, 80)); }]; [scrollViewContentView mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self);  make.edges.equalTo(scrollView);  make.size.mas_equalTo(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)); }]; [RACObserve(scrollView, contentOffset) subscribeNext:^(id x) { NSLog(x); }]; } // When the interface has multiple requests and needs to obtain data, To display interface - (void) moreRequest {/ * 1. Rac_liftSelector: withSignalsFromArray: Signals: when the incoming Signals (array) signal, Each signal sends next at least once to trigger the first selector method. 2. Use note: several signals, the method of parameter one is several parameters, each parameter corresponds to the data sent by the signal. */ */ */ */ */ */ */ */ */ */ RACSignal *request1 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {// send request1 [subscriber sendNext:@"Send request 1"];  
        returnnil; }]; RACSignal *request2 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {// send request2 [subscriber sendNext:@"Send Request 2"];  
        returnnil; }]; // Use note: several signals, parameter one method is several parameters, each parameter corresponds to the signal sent data. [self rac_liftSelector:@selector(updateUIWithR1:r2:) withSignalsFromArray:@[request1,request2]]; } // updateUI - (void)updateUIWithR1:(id)data r2:(id)data1 {NSLog(@"Update UI%@ %@",data,data1);  
}  
  
#pragma mark -- Timer- (void) RACSchedulerAndMain {/ * * * * * * * * * * * * * * * * * * * timer * * * * * * * * * * * * / / / 1. // [[RACScheduler mainThreadScheduler] afterDelay:2 schedule:^{// // NSLog(rac); // //}]; [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {NSLog(x);  // NS(@"55555555"); }]; // These are the two most commonly used methods of timers. The first method is to delay the time to do something and change the afterDelay property. The second method is to do something every time and change the interval property.Copy the code
The last

Today I write here, BELIEVE you have already started, now RAC dry things have a lot of, write these in addition to help want to start learning RxJava beginners, the most important or play a note of the role of it, good memory is better than bad writing. Communicate with each other.