Last active
October 19, 2017 07:17
-
-
Save lacyrhoades/f917b971e97fdecf9607669501ef6512 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
func debug() { | |
let manager = ThingManager() | |
let thing1 = Thing(name: "thing1") | |
manager.addThing(thing1) | |
manager.sawSomeThing(named: thing1.name) | |
print("Manager has this many things: ", manager.things.count) | |
Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { (timer) in | |
// By now, the manager should have forgotten about the thing | |
print("Manager has this many things: ", manager.things.count) | |
}) | |
} | |
struct Thing { | |
var name: String | |
} | |
class ThingManager { | |
var things: [String: Thing] = [:] | |
fileprivate var thingWatchingQueue = DispatchQueue.global() | |
fileprivate var thingWatchingTimers: [String: Timer] = [:] | |
func addThing(_ thing: Thing) { | |
self.things[thing.name] = thing | |
} | |
func sawSomeThing(named name: String) { | |
self.thingWatchingQueue.async { | |
// re-up the timer so we don't forget about that thing | |
if let timer = self.thingWatchingTimers[name] { | |
timer.invalidate() | |
} | |
self.thingWatchingTimers[name] = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false, block: { (timer) in | |
self.removeThing(named: name) | |
}) | |
} | |
} | |
func removeThing(named name: String) { | |
self.things.removeValue(forKey: name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment