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
final class Pantry { | |
let jams = Observable([Jam(flavour: .apple)]) | |
func add(jam: Jam) { | |
jams.value.append(jam) | |
} | |
} | |
struct Jam { | |
enum Flavour: String { | |
case apple, orange | |
} | |
let flavour: Flavour | |
init(flavour: Flavour) { | |
self.flavour = flavour | |
} | |
} | |
let pantry = Pantry() | |
print("Adding count and contents observers.") | |
let observer = pantry.jams.observe { (jams) in | |
print("Pantry now has \(jams.count) jars of jam.") | |
} | |
pantry.jams.observe(initial: true) { (jams) in | |
let contents = jams.map({ $0.flavour.rawValue }).joined(separator: ", ") | |
print("Jams in pantry: \(contents)") | |
} | |
print("Adding jam to pantry.") | |
pantry.add(jam: Jam(flavour: .orange)) | |
print("Removing count observer.") | |
pantry.jams.removeObserver(observer) | |
print("Adding jam to pantry.") | |
pantry.add(jam: Jam(flavour: .apple)) | |
/* | |
Adding count and contents observers. | |
Jams in pantry: apple | |
Adding jam to pantry. | |
Pantry now has 2 jars of jam. | |
Jams in pantry: apple, orange | |
Removing count observer. | |
Adding jam to pantry. | |
Jams in pantry: apple, orange, apple | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment