Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Channels #2
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]
}
}
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
You can’t perform that action at this time.