Kiss My Score
Kiss My Score allows you to easily join Facebook friends’…
ReactiveSwift makes asynchronous iOS development much easier and more powerful. We will teach you how to wrap asynchronous functions in this program.
ReactiveSwift makes asynchronous iOS development much easier and more powerful. However, when we use external libraries, the asynchronous functions they provide usually don’t work with our ReactiveSwift code. Let’s see how we can solve this problem by wrapping asynchronous functions with ReactiveSwift through an example.
Imagine the library we want to use has an asynchronous function called
mockAsyncFunction(completion:). This function waits 5 seconds and executes the
completion closure with either a
String or a
MockError. Below is the implementation of this method:
This is how we would normally use the function:
The problem with this closure-based function is that we cannot use it with other ReactiveSwift primitives, which is how to make ReactiveSwift truly powerful.
Here is how we could wrap the library’s function to make it return a
In the above function, we are returning a
SignalProducer that sends a
Error through the
observer, depending on what we get in
mockAsyncFunction's closure. Now we can use
wrappedFunction() with all our other ReactiveSwift primitives!
wrappedFunction() function in action, run the following code. (If you swap the commented code in
mockAsyncFunction, you will get an
Error from the
SignalProducer instead of a
When using ReactiveSwift in your iOS project, you don’t have to put up with closure-based external functions just because they are provided that way. Simple wrapper functions, like the one above, are all that is needed for you to continue writing reactive code.