-
-
Save jarsen/8cabf133e6aa2311322a8c82922f9223 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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