Skip to content

Instantly share code, notes, and snippets.

@vasarhelyia
Last active January 13, 2018 20:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save vasarhelyia/e4fa64096517ae966d01 to your computer and use it in GitHub Desktop.
Save vasarhelyia/e4fa64096517ae966d01 to your computer and use it in GitHub Desktop.
Brew MVVM
class Brew {
var temp: Float = 0.0
}
class BrewViewModel : NSObject {
var brew = Brew()
dynamic var temp: Float = 0.0 {
didSet {
self.brew.temp = temp
}
}
override init() {
super.init()
self.connectToHost()
}
func connectToHost() {
SIOSocket.socketWithHost("http://brewcore-demo.herokuapp.com", response: {socket in
socket.on("temperature_changed", callback: {(AnyObject data) -> Void in
self.temp = data[0] as Float
})
})
}
}
class BrewViewController: UIViewController {
@IBOutlet weak var tempLabel: UILabel!
let brewViewModel = BrewViewModel()
private var brewContext = 0
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.brewViewModel.addObserver(self, forKeyPath: "temp", options: .New, context: &brewContext)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &brewContext {
dispatch_async(dispatch_get_main_queue(), {
self.updateTempLabel((change[NSKeyValueChangeNewKey]) as Float)
})
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
func updateTempLabel(temp: Float) {
self.tempLabel.text = NSString(format:"%.2f ˚C", temp)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment