Skip to content

Instantly share code, notes, and snippets.

@davenportw15
Created May 30, 2016 04:52
Show Gist options
  • Save davenportw15/101db35fb035c384e4b2bb553bb62969 to your computer and use it in GitHub Desktop.
Save davenportw15/101db35fb035c384e4b2bb553bb62969 to your computer and use it in GitHub Desktop.
A simple example of reactive programming
// Automatically responds to changes in `value` property
class Observable<Value, Return> {
// Contents of observable
var value: Value
// Run whenever value changes
let onChange: Value -> Return
init(withInitial value: Value, onChange change: Value -> Return) {
self.value = value
self.onChange = change
}
// Returns current value
func getValue() -> Value {
return self.value;
}
// Updates value
func update(value: Value) {
self.value = value
self.onChange(self.value)
}
// Applies transform to value
func flatmap(transform: Value -> Value) {
self.update(transform(self.value));
}
}
// Example 1: Logging integers
func logInt(i: Int) {
print("logging int: ", i)
}
let intObserver = Observable(withInitial: 0, onChange: logInt)
for i in 1...10 {
intObserver.flatmap { i in i + 1 };
}
// Example 2: Saving user automatically on update
class User {
let id: Int
let username: String
var password: String
init(id: Int, username: String, password: String) {
self.id = id
self.username = username
self.password = password
}
}
func saveUser(user: User) {
print("Saving ", user.username);
}
let user = User(id: 1, username: "wdavenport", password: "testing")
let userObserver = Observable(withInitial: user, onChange: saveUser)
// Change password
userObserver.flatmap { user in
user.password = "newPassword"
return user
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment