Skip to content

Instantly share code, notes, and snippets.

@jarsen
Last active September 9, 2016 16:36
Show Gist options
  • Save jarsen/8cabf133e6aa2311322a8c82922f9223 to your computer and use it in GitHub Desktop.
Save jarsen/8cabf133e6aa2311322a8c82922f9223 to your computer and use it in GitHub Desktop.
struct AddPlayer: Command {
var session = URLSession.shared
var player: Player
func execute(state: State, reactor: Reactor<State>) {
let originalPlayers = state.players
let task = session.dataTask(with: player.putRequest()) { data, response, error in
if error {
// 3. whoops. switch back and display error
reactor.fire(event: Update(value: originalPlayers))
reactor.fire(event: DisplayError(message: "Error adding \(player.name)"))
}
else {
// handle json and ...
// 2. update with the real values from the server, hopefully the same
reactor.fire(event: Update(value: players))
}
}
// 1. optimistically assume success and immediately update UI
var optimisticPlayers = originalPlayers
optimisticPlayers.append(player)
reactor.fire(event: Update(value: optimisticPlayers))
task.resume()
}
}
// Caller uses:
reactor.fire(command: AddPlayer(player: player))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment