Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gokselkoksal/7ad6873fc9ce228d7552ea6c1d47247c to your computer and use it in GitHub Desktop.
Save gokselkoksal/7ad6873fc9ce228d7552ea6c1d47247c to your computer and use it in GitHub Desktop.
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