Last active
March 2, 2018 10:55
-
-
Save gokselkoksal/7ad6873fc9ce228d7552ea6c1d47247c to your computer and use it in GitHub Desktop.
Using Channels #2
This file contains hidden or 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
enum Theme: String { | |
case light, dark | |
} | |
class UserSettings { | |
static let shared = UserSettings(notificationCenter: .default) | |
let notificationCenter: NotificationCenter | |
var theme: Theme = .light { | |
didSet { | |
let name = ThemeDidChangeNotification.name | |
let userInfo = ThemeDidChangeNotification.userInfo(with: theme) | |
notificationCenter.post(name: name, object: self, userInfo: userInfo) | |
} | |
} | |
init(notificationCenter: NotificationCenter) { | |
self.notificationCenter = notificationCenter | |
} | |
} | |
struct ThemeDidChangeNotification { | |
static let name = Notification.Name(rawValue: "ThemeDidChangeNotification") | |
let theme: Theme | |
init?(userInfo: [AnyHashable: Any]?) { | |
if let rawTheme = userInfo?["theme"] as? String, | |
let theme = Theme(rawValue: rawTheme) { | |
self.theme = theme | |
} else { | |
return nil | |
} | |
} | |
static func userInfo(with theme: Theme) -> [AnyHashable: Any] { | |
return ["theme": theme.rawValue] | |
} | |
} |
This file contains hidden or 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
class HomeViewController: UIViewController { | |
private let userSettings = UserSettings.shared | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
subscribe() | |
} | |
func subscribe() { | |
let notificationCenter = userSettings.notificationCenter | |
notificationCenter.addObserver(forName: ThemeDidChangeNotification.name, object: userSettings, queue: .main) { (notification) in | |
guard let theme = ThemeDidChangeNotification(userInfo: notification.userInfo)?.theme else { return } | |
// Apply theme here. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment