Skip to content

Commit 1e47af3

Browse files
committed
update README with some basic Command documentation
1 parent 0367fd9 commit 1e47af3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,31 @@ extension ViewController: Subscriber {
130130

131131
By subscribing and subscribing in `viewDidAppear`/`viewDidDisappear` respectively, we ensure that whenever this view controller is visible it is up to date with the latest application state. Upon initial subscription, the reactor will send the latest state to the subscriber's `update` function. Button presses forward events back to the reactor, which will then update the state and result in subsequent calls to `update`. (note: the Reactor always dispatches back to the main thread when it updates subscribers, so it is safe to perform UI updates in `update`.)
132132

133+
## Commands
134+
135+
Sometimes you want to fire an `Event` at a later point, for example after a network request, database query, or other asynchronous operation. In these cases, `Command` helps you interact with the `Reactor` in a safe and consistent way.
136+
137+
```swift
138+
struct CreatePlayer: Command {
139+
var session = URLSession.shared
140+
var player: Player
141+
142+
func execute(state: RPGState, reactor: Reactor<RPGState>) {
143+
let task = session.dataTask(with: player.createRequest()) { data, response, error in
144+
// handle response appropriately
145+
// then fire an update back to the reactor
146+
reactor.fire(event: AddPlayer(player: player))
147+
}
148+
task.resume()
149+
}
150+
}
151+
152+
// to fire a command
153+
reactor.fire(command: CreatePlayer(player: myNewPlayer))
154+
```
155+
156+
Commands get a copy of the current state, and a reference to the Reactor so they can fire Events as necessary.
157+
133158
## Middleware
134159

135160
Sometimes you want to do something with an event besides just update application state. This is where `Middleware` comes into play. When you create a `Reactor`, along with the initial state, you may pass in an array of middleware. Each middleware gets called every time an event is passed in. Middleware is not allowed to mutate the state, but it does get a copy of the state along with the event. Middleware makes it easy to add things like logging, analytics, and error handling to an application.

0 commit comments

Comments
 (0)