Wrapping Asynchronous Functions with ReactiveSwift
Introduction
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 those functions with ReactiveSwift through an example.
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 SignalProducer
:
In the above function, we are returning a SignalProducer
that sends a Value
or an Error
through the observer
, depending on what we get in mockAsyncFunction
's closure. Now we can use wrappedFunction()
with all our other ReactiveSwift primitives!
To see 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 Value
)
All the code could be viewed here. Remember to import ReactiveSwift before trying.
Conclusion
When using ReactiveSwift in your iOS project, you don’t have to put up with closure-base external functions just because they are provided that way. Simple wrapper functions, like the one above, are all that are needed for you to continue writing reactive code.