Reactivecocoa and functional reactive programming

Source: Internet
Author: User

What is functional reactive programming

Http://limboy.me/ios/2013/06/19/frp-reactivecocoa.html

Functional reactive Programming (hereinafter referred to as FRP) is a programming paradigm that responds to change. Let's take a look at a small piece of code

a = 2b = 2c = a + b // c is 4b = 3// now what is the value of c?

If you use FRP, c the value will b change as the value changes, so it is called "responsive programming." A more intuitive example is Excel, which changes the results of a cell when it changes its contents.

FRP provides a signaling mechanism to achieve this effect by recording the change in value by means of a signal. Signals can be superimposed, split, or merged. By combining the signals, there is no need to listen for a value or event.

This is very useful in heavy-interactive applications. Take registration as an example:

The status of the Submit button is bound to the state of the input box, such as the required input box is not completed, the submit button is gray, that is, not point, if the Submit button is not point, then the text becomes gray, or it becomes blue, if you are committing, then the text color of the input box becomes gray, and is not point, Otherwise it becomes the default color and can point, if the registration succeeds in the status bar to display success information, otherwise display error message, and so on.

You can see that there are so many linkage in the registration page alone, in JavaScript can be handled by event monitoring, iOS more is the delegate mode, is essentially the distribution and response of events. The disadvantage of this approach is not intuitive enough, especially in the case of complex logic. That's why even though Nodejs is efficient, many people are deterred by the fact that JavaScript's callback style and asynchronous mode do not conform to normal programming habits.

There are two main benefits of using FRP: Intuitive and flexible. Intuitive code is easy to write, read and maintain, with flexible features that allow you to respond to perverted needs.

Reactivecocoa

Reactivecocoa is a project on GitHub that was open source last year and is the implementation of FRP on the iOS platform. The core of the FRP is the signal, which is represented by the signal in Reactivecocoa (RAC) RACSignal , which is a data stream that can be bound and passed.

Can think of the signal as a faucet, but the inside is not water, but the glass ball (value), the diameter of the same as the water pipe, so that the glass ball is arranged in order, there will be no side of the situation (data are linear processing, there will be no concurrency). The tap switch is off by default and will not open unless the receiver (subscriber) is available. So as soon as a new glass ball comes in, it is automatically transmitted to the receiver. Can add a filter on the faucet, does not conform to pass, can also add a change device, the ball to meet their own needs (map). You can also combine multiple taps into a new faucet (combinelatest:reduce:) so as long as one of the taps has a glass ball coming out, this new combined faucet will get the ball.

This model is shown below with a simple demo.

If a property of an object wants to bind a message, you can use RAC this macro, which is equivalent to a faucet for a glass ball.

Rac(Self.Submitbutton,Enabled)=[RacsignalCombinelatest:@[Self.Usernamefield.Rac_textsignal,self. Passwordfield. Rac_textsignal] reduce:^id< Span class= "P" > (nsstring *username nsstring *password) { return @ (username. Length >= 6 && password length >= 6) ;}];   

This way, if the user name and password box are longer than 6, the submit button is enable. Conversely, if it does not meet the requirements, it will be in a non-open state.

You can see that usernameField there is a new property rac_textSignal , which is added by the RAC in the UITextField category and can be used directly.

The Great unity of RAC

RAC unifies the processing of KVO, UI Event, Network request, and Async work because they are essentially changes in value (values over time).

KVO

RAC can be used to monitor property changes, which is similar to KVO, but uses block instead-observeValueForKeyPath:ofObject:change:context:

[RACAble(self.username) subscribeNext:^(NSString *newName) { NSLog(@"%@", newName);}];

It is not much more comfortable to use than the KVO. More powerful than KVO is the signal can be chained up (chain)

Only when the name begins with ' J ' will it be recorded[[Racable(Self. username) filter:^(nsstring *newName) { return [  NewName hasprefix:@ "J"]; }] subscribenext:^(nsstring *newName) { NSLog(@ "% @ ", newName); }]; 
UI Event

RAC also provides a number of category for the system UI to facilitate the creation and delivery of messages, such as buttons clicked or text box changes and so on, in the example above, self.firstNameField.rac_textSignal when the corresponding text box changes, will automatically add new data to the data stream, the other messages bound to the message will receive new data, If there is subscriber, it will be triggered automatically.

Network Request && Async work

These can be done by customizing the signal, which RACSubject is (inherited from RACSignal , can be understood as a higher degree of freedom Signal). An asynchronous network operation, for example, can return a subject and bind the subject to a subscriber or another signal.

-(void)Dotest{Racsubject*Subject=[SelfDoRequest];[SubjectSubscribenext:^(NSString*Value){NSLog(@ "value:%@",Value);}];}-(Racsubject*)DoRequest{Racsubject*Subject=[RacsubjectSubject];The requested content is received after 2 seconds of simulationtriggered only 1 timesAlthough Subscribenext did nothing, the map would not be executed if not.Subscribenext is the definition of a receiver[[[[RacsignalInterval:2]Take:1]Map:^id (id _< Span class= "P" >) {//the value is from URL request nsstring *value = @ "content fetched from web" [subject sendnext:value ; return nil}] subscribenext:^ (_) {}]; return subject;}       
Summary

Simply draw the next diagram, listing some of the main points

The above is just about the usage scenarios and usage of RAC, and more examples can be viewed on the project homepage.

Reference
    • http://www.teehanlax.com/blog/getting-started-with-reactivecocoa/
    • https://speakerdeck.com/andrewsardone/reactivecocoa-at-mobidevday-2013

Reactivecocoa and functional reactive programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.