Reactor provides a Model layer with minimum configuration. It makes use of the following elements to achieve that:
- Network
- Parser
- Persistence
- ReactiveCocoa as its only dependency.
Reactor then uses flows (represented by the ReactorFlow<T>
), that are typically seen in applications. For example:
- Does persisted data exist and is it valid?
- Yes: Use it ✅
- No: Fetch data from the network
1. Do we have an internet connection?
- Yes: make the Request.
- Parse the data and persist it (send any error that might occur) ✅
- Request failed: send an error ❌
- No: send an error ❌
This particular flow is provided out of the box by Reactor. In the future we will provide others.
- You are are starting a new project. 🌳
- You are in the process of defining your model layer. 🛠
- You are creating a prototype or demo and you need something working quickly. 🚀
- You don't feel comfortable enough with ReactiveCocoa and need some help with the setup. 🆒
- You already have your Model layer in place, but you think Reactor could formalize your flows. ✨
- You have an unusual flow, that doesn't really fit the
ReactorFlow<T>
. ⛔️ - You already have a Model layer and you feel it wouldn't really benefit you in any way. 😞
- You already have a parser and your own network library (Alamofire for example). 🔥
- After checking the Advance usage, Reactor doesn't provide what you need. 😭😭
github "MailOnline/Reactor"
# Since there is already a podfile named `Reactor`, we are using `MOReactor`.
pod 'MOReactor', '~> 0.9'
For Reactor to work, you need to make sure your Model objects comply with the Mappable
protocol. This protocol allows you to encode and decode an object. This is necessary for parsing the object (coming from the network) and storing it on disk.
Let's use the Author
struct as an example (this can be found in the Unit tests). The first step is to make the Author
struct compliant with the Mappable
protocol:
struct Author {
let name: String
}
extension Author: Mappable {
static func mapToModel(object: AnyObject) -> Result<Author, MappedError> {
guard
let dictionary = object as? [String: AnyObject],
let name = dictionary["name"] as? String
else { return Result(error: MappedError.Custom("Invalid dictionary @ \(Author.self)\n \(object)"))}
let author = Author(name: name)
return Result(value: author)
}
func mapToJSON() -> AnyObject {
return ["name": self.name]
}
}
Note: The above implementation, is just an example, you are free to use whatever means you prefer.
The first function mapToModel
is what allows a model object to be created (JSON ➡️ Model). The second function mapToJSON
is the inverse (Model ➡️ JSON).
The second step would be:
let baseURL = NSURL(string: "https://myApi.com")!
let reactor = Reactor<Author>(persistencePath: path, baseURL:baseURL)
Now that you have the reactor
ready, it exposes two functions:
func fetch(resource: Resource) -> SignalProducer<T, Error>
func fetchFromNetwork(resource: Resource) -> SignalProducer<T, Error>
We find that these are the two most common scenarios:
- When you get to a new screen, you try to get some data. In this case, Reactor checks the persistence store first and if it fails it will fallback to the network.
- You want fresh data, so Reactor will use the network.
The final piece is the Resource
, which is nothing more than a struct that encapsulates how the request will be made:
- path
- query
- body
- HTTP headers
- HTTP method
If it doesn't make sense to persist data, you pass the persistencePath
as an empty string (""
) or:
let baseURL = NSURL(string: "https://myApi.com")!
let reactor = Reactor<Author>(baseURL:baseURL)
In the future will make this explicit via a ReactorConfiguration
. As for the mapToJSON
function, you can simply return an NSNull
:
func mapToJSON() -> AnyObject {
return NSNull()
}
In order to make most of Reactor, keep the following in mind (these are ReactorFlow<T>
's properties):
var networkFlow: Resource -> SignalProducer<T, Error>
var loadFromPersistenceFlow: Void -> SignalProducer<T, Error>
var saveToPersistenceFlow: T -> SignalProducer<T, Error>
All three properties are mutable (var
) on purpose, so you can extend specific behaviours. For example, you might be interested in knowing why loadFromPersistenceFlow
is failing and log it. With the default flow, this is not possible to do, because if loadFromPersistenceFlow
fails, the network flow will kick in and the error is lost.
A way to accomplish this, is by creating a default flow and then extending it:
let baseURL = NSURL(string: "https://myApi.com")!
let reactor = Reactor<Author>(persistencePath: path, baseURL:baseURL)
let extendedPersistence = reactor.loadFromPersistenceFlow().on(failure: { error in print(error) })
reactor.loadFromPersistenceFlow = { extendedPersistence }
You can further decompose the flow, since all the core pieces are exposed in the public API. More specifically:
Network
and theConnection
protocolParser
InDiskPersistenceHandler<T>
The default flow provided by Reactor (Intro) is something you are welcome to use, but not tied to. Keep in mind the following when creating your own flows:
The Reactor<T>
's fetch
function axiom:
- the
loadFromPersistenceFlow
will always be called first. If it fails,fetchFromNetwork
is called.
The Reactor<T>
's fetchFromNetwork
function axiom:
- the
networkFlow
will always be called first, if it succeeds it will be followed bysaveToPersistenceFlow
.
Reactor is licensed under the MIT License, Version 2.0. View the license file
Copyright (c) 2015 MailOnline
Header image by Henrique Macedo.