ReactiveCocoa Tutorial – The Definitive Introduction: Part
As an iOS developer,nearly every line of code you write is in reaction to some event; a button tap,a received network message,a property change (via Key Value Observing) or a change in user’s location via CoreLocation are all good examples. However,these events are all encoded in different ways; as actions,delegates,KVO,callbacks and others. ReactiveCocoa defines a standard interface for events,so they can be more easily chained,filtered and composed using a basic set of tools. Sound confusing? Intriguing? … Mind blowing? Then read on :] ReactiveCocoa combines a couple of programming styles:
For this reason,you might hear ReactiveCocoa described as a Functional Reactive Programming (or FRP) framework. Rest assured,that is as academic as this tutorial is going to get! Programming paradigms are a fascinating subject,but the rest of this ReactiveCocoa tutorials focuses solely on the practical value,with work-through examples instead of academic theories. The Reactive PlaygroundThroughout this ReactiveCocoa tutorial,you’ll be introducing reactive programming to a very simple example application,the ReactivePlayground. Download the starter project,then build and run to verify you have everything set up correctly. ReactivePlayground is a very simple app that presents a sign-in screen to the user. Supply the correct credentials,which are,somewhat imaginatively,user for the username,and password for the password,and you’ll be greeted by a picture of a lovely little kitten. Awww! How cute! Right now it’s a good point to spend a little time looking through the code of this starter project. It is quite simple,so it shouldn’t take long. Open RWViewController.m and take a look around. How quickly can you identify the condition that results in the enabling of the Sign In button? What are the rules for showing / hiding the With the use of ReactiveCocoa,the underlying intent of the application will become a lot clearer. It’s time to get started! Adding the ReactiveCocoa FrameworkThe easiest way to add the ReactiveCocoa framework to your project is via CocoaPods. If you’ve never used CocoaPods before it might make sense to follow the Introduction To CocoaPods tutorial on this site,or at the very least run through the initial steps of that tutorial so you can install the prerequisites. Note: If for some reason you don’t want to use CocoaPods you can still use ReactiveCocoa,just follow the Importing ReactiveCocoa steps in the documentation on GitHub. If you still have the ReactivePlayground project open in Xcode,then close it now. CocoaPods will create an Xcode workspace,which you’ll want to use instead of the original project file. Open Terminal. Navigate to the folder where your project is located and type the following:
This creates an empty file called Podfile and opens it with TextEdit. Copy and paste the following lines into the TextEdit window:
This sets the platform to iOS,the minimum SDK version to 7.0,and adds the ReactiveCocoa framework as a dependency. Once you’ve saved this file,go back to the Terminal window and issue the following command:
You should see an output similar to the following:
This indicates that the ReactiveCocoa framework has been downloaded,and CocoaPods has created an Xcode workspace to integrate the framework into your existing application. Open up the newly generated workspace,RWReactivePlayground.xcworkspace,and look at the structure CocoaPods created inside the Project Navigator: You should see that CocoaPods created a new workspace and added the original project,RWReactivePlayground,together with a Pods project that includes ReactiveCocoa. CocoaPods really does make managing dependencies a breeze! You’ll notice this project’s name is Time To PlayAs mentioned in the introduction,ReactiveCocoa provides a standard interface for handling the disparate stream of events that occur within your application. In ReactiveCocoa terminology these are called signals,and are represented by the Open the initial view controller for this app,RWViewController.m,and import the ReactiveCocoa header by adding the following to the top of the file:
You aren’t going to replace any of the existing code just yet,for now you’re just going to play around a bit. Add the following code to the end of the
Build and run the application and type some text into the username text field. Keep an eye on the console and look for an output similar to the following:
You can see that each time you change the text within the text field,the code within the block executes. No target-action,no delegates — just signals and blocks. That’s pretty exciting! ReactiveCocoa signals (represented by
The ReactiveCocoa framework uses categories to add signals to many of the standard UIKit controls so you can add subscriptions to their events,which is where the But enough with the theory,it’s time to start making ReactiveCocoa do some work for you! ReactiveCocoa has a large range of operators you can use to manipulate streams of events. For example,assume you’re only interested in a username if it’s more than three characters long. You can achieve this by using the
If you build and run,then type some text into the text field,you should find that it only starts logging when the text field length is greater than three characters:
What you’ve created here is a very simple pipeline. It is the very essence of Reactive Programming,where you express your application’s functionality in terms of data flows. It can help to picture these flows graphically: In the above diagram you can see that the At this point it’s worth noting that the output of the
Because each operation on an
Note: ReactiveCocoa makes heavy use of blocks. If you’re new to blocks,you might want to read Apple’s
Blocks Programming Topics. And if,like me,you’re familiar with blocks,but find the syntax a little confusing and hard to remember,you might find the amusingly titled
f*****gblocksyntax.com quite useful! (
We censored the word to protect the innocent,but the link is fully functional.)
A Little CastIf you updated your code to split it into the various
The implicit cast from
Build and run to confirm this works just as it did previously. What’s An Event?So far this tutorial has described the different event types,but hasn’t detailed the structure of these events. What’s interesting is that an event can contain absolutely anything! As an illustration of this point,you’re going to add another operation to the pipeline. Update the code you added to
If you build and run you’ll find the app now logs the length of the text instead of the contents:
The newly added map operation transforms the event data using the supplied block. For each next event it receives,it runs the given block and emits the return value as a next event. In the code above,the map takes the For a stunning graphic depiction of how this works,take a look at this image: As you can see,all of the steps that follow the
Note: In the above example the
text.length property returns an
NSUInteger ,which is a primitive type. In order to use it as the contents of an event,it must be boxed. Fortunately the
Objective-C literal syntax provides and option to do this in a rather concise manner –
@(text.length) .
That’s enough playing! It’s time to update the ReactivePlayground app to use the concepts you’ve learned so far. You may remove all of the code you’ve added since you started this tutorial. Creating Valid State SignalsThe first thing you need to do is create a couple of signals that indicate whether the username and password text fields are valid. Add the following to the end of
As you can see,the above code applies a The next step is to transform these signals so that they provide a nice background color to the text fields. Basically,you subscribe to this signal and use the result to update the text field background color. One viable option is as follows:
(Please don’t add this code,there’s a much more elegant solution coming!) Conceptually you’re assigning the output of this signal to the Fortunately,ReactiveCocoa has a macro that allows you to express this with grace and elegance. Add the following code directly beneath the two signals you added to
The This is a very elegant solution,don’t you think? One last thing before you build and run. Locate the
That will clean up the non-reactive code. Build and run the application. You should find that the text fields look highlighted when invalid,and clear when valid. Visuals are nice,so here is a way to visualize the current logic. Here you can see two simple pipelines that take the text signals,map them to validity-indicating booleans,and then follow with a second mapping to a Are you wondering why you created separate Combining signalsIn the current app,the Sign In button only works when both the username and password text fields have valid input. It’s time to do this reactive-style! The current code already has signals that emit a boolean value to indicate if the username and password fields are valid; At the end of
The above code uses the
Note: The
RACSignal combine methods can combine any number of signals,and the arguments of the reduce block correspond to each of the source signals. ReactiveCocoa has a cunning little utility class,RACBlockTrampoline that handles the reduce block’s variable argument list internally. In fact,there are a lot of cunning tricks hidden within the ReactiveCocoa implementation,so it’s well worth pulling back the covers!
Now that you have a suitable signal,add the following to the end of
Before running this code,it’s time to rip out the old implementation. Remove these two properties from the top of the file:
From near the top of
Also remove the Finally,make sure to remove the call to If you build and run,check the Sign In button. It should be enabled because the username and password text fields are valid,as they were before. An update to the application logic diagram gives the following: The above illustrates a couple of important concepts that allow you to perform some pretty powerful tasks with ReactiveCocoa;
The result of these changes is the application no longer has private properties that indicate the current valid state of the two text fields. This is one of the key differences you’ll find when you adopt a reactive style — you don’t need to use instance variables to track transient state. Reactive Sign-inThe application currently uses the reactive pipelines illustrated above to manage the state of the text fields and button. However,the button press handling still uses actions,so the next step is to replace the remaining application logic in order to make it all reactive! The Touch Up Inside event on the Sign In button is wired up to the Open up Main.storyboard,locate the Sign In button,ctrl-click to bring up the outlet / action connections and click the x to remove the connection. If you feel a little lost,the diagram below kindly shows where to find the delete button: You’ve already seen how the ReactiveCocoa framework adds properties and methods to the standard UIKit controls. So far you’ve used Returning to
The above code creates a signal from the button’s Build and run to confirm the message actually logs. Bear in mind that the button will enable only when the username and password are valid,so be sure to type some text into both fields before tapping the button! You should see messages in the Xcode console similar to the following:
Now that the button has a signal for the touch event,the next step is to wire this up with the sign-in process itself. This presents something of a problem — but that’s good,you don’t mind a problem,right? Open up
This service takes a username,a password and a completion block as parameters. The given block is run when the sign-in is successful or when it fails. You could use this interface directly within the
Note: A dummy service is being used in this tutorial for simplicity,so that you don’t have any dependencies on external APIs. However,you’ve now run up against a very real problem,how do you use APIs not expressed in terms of signals?
Creating SignalsFortunately,it’s rather easy to adapt existing asynchronous APIs to be expressed as a signal. First,remove the current Stay in RWViewController.m and add the following method:
The above method creates a signal that signs in with the current username and password. Now for a breakdown of its component parts. The above code uses the The block is passed a single The return type for this block is an As you can see,it’s surprisingly simple to wrap an asynchronous API in a signal! Now to make use of this new signal. Update the code you added to the end of
The above code uses the If you build and run,then tap the Sign In button,and take a look at the Xcode console,you’ll see the result of the above code … … and the result isn’t quite what you might have expected!
The Time to illustrate this pipeline so you can see what’s going on: The The situation above is sometimes called the signal of signals; in other words an outer signal that contains an inner signal. If you really wanted to,you could subscribe to the inner signal within the outer signal’s Signal of SignalsThe solution to this problem is straightforward,just change the
This maps the button touch event to a sign-in signal as before,but also flattens it by sending the events from the inner signal to the outer signal. Build and run,and keep an eye on the console. It should now log whether the sign-in was successful or not:
Exciting stuff! Now that the pipeline is doing what you want,the final step is to add the logic to the
The Build and run to enjoy the kitten once more! Meow! Did you notice there is one small user experience issue with the current application? When the sign-in service validates the supplied credentials,is should disable the Sign In button. This prevents the user from repeating the same sign-in. Furthermore,if a failed sign-in attempt occurred,the error message should be hidden when the user tries to sign-in once again. But how should you add this logic to the current pipeline? Changing the button’s enabled state isn’t a transformation,filter or any of the other concepts you’ve encountered so far. Instead,it’s what is known as a side-effect; or logic you want to execute within a pipeline when a next event occurs,but it does not actually change the nature of the event itself. Adding side-effectsReplace the current pipeline with the following:
You can see how the above adds a The It’s time to update the pipeline diagram to include this side effect. Bask in all it’s glory: Build and run the application to confirm the Sign In button enables and disables as expected. And with that,your work is done – the application is now fully reactive. Woot! If you got lost along the way,you can download the final project (complete with dependencies),or you can obtain the code from GitHub,where there is a commit to match each build and run step in this tutorial. Note: Disabling buttons while some asynchronous activity is underway is a common problem,and once again ReactiveCocoa is all over this little snafu. The ConclusionsHopefully this tutorial has given you a good foundation that will help you when starting to use ReactiveCocoa in your own applications. It can take a bit of practice to get used to the concepts,but like any language or program,once you get the hang of it it’s really quite simple. At the very core of ReactiveCocoa are signals,which are nothing more than streams of events. What could be simpler than that? With ReactiveCocoa one of the interesting things I have found is there are numerous ways in which you can solve the same problem. You might want to experiment with this application,and adjust the signals and pipelines to change the way they split and combine. It’s worth considering that the main goal of ReactiveCocoa is to make your code cleaner and easier to understand. Personally I find it easier to understand what an application does if its logic is represented as clear pipelines,using the fluent syntax. In the second part of this tutorial series you’ll learn about more advanced subjects such as error handing and how to manage code that executes on different threads. Until then,have fun experimenting!
转自:http://www.raywenderlich.com/62699/reactivecocoa-tutorial-pt1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |