The weird world of observable keys πŸ”‘πŸ‘€

The get that keeps on getting.

Solution

Given a bus:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Foundation
struct Value : Event {
let key: String
let val: Any?
}
protocol Store {
func get(_ key: String)
func set(_ key: String, _ val: Any?)
}
class LocalStore : Store {
let db: UserDefaults
let bus: Bus
init(db: UserDefaults, bus: Bus){
self.db = db
self.bus = bus
}
func get(_ key: String) {
let val = db.object(forKey: key)
bus.pub(Value(key: key, val: val))
}
func set(_ key: String, _ val: Any?){
db.set(val, forKey: key)
bus.pub(Value(key: key, val: val))
}
}
let bus = Bus()
bus.sub(StdoutSubscriber())
let local = LocalStore(db: UserDefaults.standard, bus: bus)
local.set("foo", "bar")
local.get("foo")

A couple features I like:

Problem

If rationalizing events bubbling up from UI and disparate data sources is challenging, normalizing to a single bus interface may be helpful.

Feedback

Thoughts? Suggestions? Hit me up @erikeldridge

License

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 International License, and code samples are licensed under the MIT license.