Last active
June 3, 2018 16:11
-
-
Save alfianlosari/cdb9064ce2b796bbe76c5ebf3e7da258 to your computer and use it in GitHub Desktop.
EmailViewModel
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
import Foundation | |
class EmailViewModel: NSObject { | |
private let emailModel: EmailModel | |
@objc dynamic var emailTextValue: String | |
@objc dynamic var isValidValue: Bool | |
private var emailTextObserver: NSObjectProtocol? | |
private var isValidObserver: NSObjectProtocol? | |
init(emailModel: EmailModel) { | |
self.emailModel = emailModel | |
self.emailTextValue = emailModel.value | |
self.isValidValue = emailModel.isValid | |
super.init() | |
self.emailTextObserver = NotificationCenter.default.addObserver(forName: EmailModel.valueDidChange, object: nil, queue: nil, using: { [weak self] (note) in | |
self?.emailTextValue = note.userInfo?[\EmailModel.value] as? String ?? "" | |
}) | |
self.isValidObserver = NotificationCenter.default.addObserver(forName: EmailModel.isValidDidChange, object: nil, queue: nil, using: { [weak self] (note) in | |
self?.isValidValue = note.userInfo?[\EmailModel.isValid] as? Bool ?? false | |
}) | |
} | |
public func updateEmailTextValue(_ value: String) { | |
self.emailModel.value = value | |
} | |
deinit { | |
if let emailTextObserver = emailTextObserver { | |
NotificationCenter.default.removeObserver(emailTextObserver, name: EmailModel.valueDidChange, object: nil) | |
} | |
if let isValidObserver = isValidObserver { | |
NotificationCenter.default.removeObserver(isValidObserver, name: EmailModel.isValidDidChange, object: nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment