- Introduction: What is Reactive Cocoa? What does functional and reactive mean, in terms of programming? Why is it useful, and generally a good practice?
- Getting started: How do I set up my project to start developing with RAC?
- Basics: Classes and methods used in RAC. General data flow representation.
- A small task: A short example of code and output behaviour
- Bigger picture: What else is RAC capable of?
- Summary: Where can I find more information, documentations? What did I learn from the sample application?
Most people, who have some experience in the field of software development have heard, or read about Functional and Reactive programming at least at one point in their lives. If you are one of them, you’ve come to the right place. If not, it’s all the same. Whether you are a senior developer looking for ways to improve the performance of your apps, an adventurous freelancer seeking new coding styles, or a novice still expanding his knowledge on mobile: Reactive Cocoa will certainly come in handy, as it incorporates both Functional and Reactive technologies into a neat and simple framework.
Worry not, there is tons of support for Swift out there. However, this article uses the Objective-C implementation of RAC, because we know there are still a bunch of applications that could benefit from it!
So why is RAC so amazing?
First of all, it’s Functional: It makes use of functions that take other functions as arguments.
Secondly, it’s Reactive: It’s focused on the flow of data and change, instead of constantly assigning new values to variables. It handles assignments on its own, as the bits flow down the river of data.
Functional and Reactive programming slightly counteract each other in certain ways, but RAC takes the best of both worlds, providing immense practical value, when implemented. This article focuses on initially using the framework, with examples and explanations to understand it better.
2. Getting Started
Setting up the environment is easy as pie: just add the ReactiveCocoa framework to your project! Using CocoaPods is strongly recommended. The actual usage of the framework will be explained later in the samples.
Start a new project, add a UITextField outlet to your root viewcontroller, then add
to the header file.
An important thing to mention is that the Objective-C implementation of RAC relies heavily on blocks. If you are not experienced with blocks, you can always visit this website. (There is a good reason I’m not writing down its name, you’ll see ).
3. Basics of Reactive Cocoa
In mobile platform development, a huge portion of our code is a reaction to all kinds of events, be it button taps, recognised gestures, NSNotifications, Key-Value Observing, etc. The bottom line is, something happened. These happenings are represented by the Event type, which is the simple most important thing in the whole picture. When an observable event occurs, these objects are generated and sent to Observers over Signals (more about these a bit later).
Events can represent either a new value, or the termination of a process. Enumerated as follows:
- Next: The event’s source produced a new value, ready to be observed and handled.
- Failed: An error occurred before the signal could finish.
- Completed: The signal went through with no problems, and value generation is now stopped.
- Interrupted: The signal was neither successful, nor unsuccessful. In other words, it was cancelled.
Objects of the Signal type are series of events, and can be observed. Signals represent event streams in progress, e.g. user input. As data are received, events are sent on the signal, and all observers receive said events at the same time. In order to see a signal’s events, the user must observe it. Signals are push-based, so observing them has no side effect, and there is no way to influence their behaviour from the receiving end.
The lifetime of a signal includes any number of Next events, and exactly one terminating event (Failed, Completed, or Interrupted).
Manipulating a signal’s value can be done by applying a primitive to their Next events, these are filter, map, and reduce. Multiple signals can be manipulated together with the zip primitive.
Using a pipe with the Signal.pipe() command produces a signal that can be controlled manually, which is useful when a non-RAC class works together with an RAC class.
Let’s take a look at this piece of code:
Let’s assume we have a UITextField, and we’d like to log its input to the standard output. Normally, we would have to add our viewcontroller as the target to the textfield, define a function to call, and implement this behaviour separately. With RAC, every standard UIControl element has a signal for its standard events, so all we have to do is subscribe to the appropriate signal, then tell our program what we want to do with the information. After the subscription has been done, and we start typing into the textfield and our output will look like this:
As you can see, we are observing every single value change in the text field. This is nice and all, but there is a lot more we can do with event flows.
Let’s say we need a number, instead of a string, for future purposes. We don’t want any non-numeric characters getting in our way, or constantly having to convert the textfield’s value into a number. This is where the filter and map primitives come in.
First, we need to check if the textfield’s value is actually numeric, then convert it into an NSInteger.
We start off by checking the value:
The primitive filter takes an argument of any kind, and returns a boolean value. What it actually does is filtering (how surprising) the incoming values, only letting through the ones we told it to. Note that it doesn’t change the original value observed through the signal, it’s just a gate to keep out everyone without a valid passport. Currently, every purely numeric string that’s at least one digit long will go through, others go down the drain.
Notice anything else? That’s right, the return value of (almost) every signal is another signal, even if primitives were applied to it. It can be assigned to a variable, able to be accessed from multiple other sources. This allows data flows to be forked, which is probably one of the most useful things about signals.
Onto the next step! We have a signal that provides us with numeric strings from our textfield, now we need to convert it to an NSInteger. Let’s add a small twist, and take the number’s remainder divided by 4.
Using the map primitive, we’re able to transform any value to any value, however we might desire. (The logic is similar to how programmers convert caffeine into code.) As you can see, these primitives can be chained (almost) infinitely. An important thing to remember is that signal chains can only take objects as their arguments, and can only return objects, that’s why we used the @() operator, to box our integers into objects.
Because we know that the numericTextSignal signal provides NSString objects, it’s safe to change the argument type too, there’s no need to manually cast it.
We already know that signals can be forked, what about merging them? Synchronizing data is crucial in mobile applications, but fear not, RAC has a great solution: the combineLatest:reduce primitive.
First off, let’s do some forking:
Now we have 3 new signals, each returning a boxed boolean value of whether the received number is divisible by 3, 4, and 5, respectively.
All we need is the combining:
If you start typing numbers into the textfield, you will start seeing the results. Try 60!
The primitive combineLatest:reduce takes all given signals and their outputs, and returns a new signal, similar to map. The key difference here is that we can observe multiple signals at once. Whenever one of the observed signals produces a new value, their combination is instantly evaluated. This is extremely useful when working in environments that act upon a large number of conditions, for example, games. Exciting, huh?
5. Creating your own signal
So far we’ve only used signals provided by native elements of the platform. In most cases, people use 3rd party libraries, and/or their already existing code to speed up development. So how do we connect our other classes with the RAC data flow? A good example would be a login service with a success/failure completion block. We make an asynchronous request, wait for the response, and then what?
Well, the answer is surprisingly easy: Let’s create our own signal that provides the server’s response as its value.
This method creates a signal that tries to sign in with our currently entered credentials.
The block that describes the signal created is a single argument, when there is a subscriber to this signal, the code within the block will execute. It is passed a subscriber instance that conforms to the RACSubscriber protocol, this allows us to emit events towards them. We can send any number of Next events, followed by a terminating event, in this case, Completed.
The block’s return type is RACDisposable, which is useful when there is additional clean-up work in case of a cancellation, but it’s not needed now, so we return nil. Now let’s make use of this signal!
Upon pressing the signInButton, the flattenMap primitive transforms the touch event into our previously written signal, then logs the result. It works very similar to map, and there is a good reason why it’s used here. If we use map, the forwarded signal would be a “signal that contains a signal”, and by flattening it, we can access the innermost signal. They can try to hide, but we’ll always find them!
Naturally, going into deep details of RAC would take tons of time, so I’m not going to do that (thank me later ). Hopefully this article was enough to demonstrate some of the strengths of this framework, and give you a fresh view of handling large rivers of data. These examples are fairly simple, but using this logic can lead to great success even in more complex situations.
If you are interested in learning more about this fantastic addition to our greyish default tools, make sure to visit the official GitHub website. You’ll find tons of documentation, platform and language support, and more! Have fun experimenting, don’t be afraid to shape your pipelines! Or riverbeds… whatever floats your boat.
Latest posts by Tamás Keller (see all)
- How Can I Use WebSocket on iOS? - March 22, 2017
- Dynamic Constraint Calculator for iOS - November 28, 2016
- Reactive Cocoa: A 6 Step Guide - June 2, 2016
- Everything You Need to Know About JSONJoy, SwiftyJSON & OCMapper - May 12, 2016