December 30th, 2015
Shirley is a minimal request framework for Swift programs. It uses ReactiveCocoa signal producers as a unified method for asynchronous data delivery, instead of callback functions. This allows disparate responses to be unified, with a single stream-based system.
The central type of the framework is a session, represented by the
Session is a closure-based implementation, which can also be used for type erasure. Sessions can be thought of as “signal producer producers” – they implement a single function that transforms a request value into a signal producer:
SessionType also requires type aliases for
Error, so that the type signature for
producerForRequest(:) can be defined:
producerForRequest(:) alone requires response values to be interpreted as
SessionType declares. Shirley solves this issue by allowing sessions to be transformed into derived sessions. For example, let’s say we have
Post types, and we want to create sessions that will process a JSON representation of each:
This creates four sessions, all of which use
baseSession to execute their requests. The request type can also be transformed. Let’s assume that
User values have an
identifier, and we’d like to be able to request a user by its identifier:
Integration with Foundation
Although Shirley is generic, it provides support for
NSURLSession, which is extended to conform to
NSURLSession accepts requests of type
NSURLRequest, produces values of type
Message<NSURLResponse, NSData>, and produces errors of type
Message is a small container type provided by Shirley for the
NSURLSession extensions. Like
Session, messages are backed by a protocol and are generic, so they are not limited to use with
Additionally, some of the extensions to
SessionType are valuable when working with
Message<NSHTTPURLResponse, Body>, failing with an error if the response is not of type
Message<Response, AnyObject>, using
NSJSONSerialization, failing with the error provided by
NSJSONSerializationif the data is not valid JSON.
Body, dropping the response value.
Of course, custom transforms can also be applied to
Shirley requires ReactiveCocoa 4.0.