Article in iOS App Development category.

Wrapping Asynchronous Functions with ReactiveSwift

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.

Asynchronous iOS Development: Wrapping Functions with ReactiveSwift

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:

Mock external library definitions for asynchronous ios development

This is how we would normally use the function:

simple use of ios asynchronous development

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:

wrapping asynchronous functions

In the above function, we are returning a SignalProducer that sends a Valueor 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)

asynchronous reactiveswift function

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-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.

More Articles By anovak

Recent Articles

Previous post Chef's Feed May 22, 2018
Next post Fueled’s Guide To GDPR For Mobile Applications May 24, 2018