Skip to content

Instantly share code, notes, and snippets.

@kien-hoang
Created February 1, 2023 11:04
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 kien-hoang/74930e56a7867e5940a9bc9077af2e7a to your computer and use it in GitHub Desktop.
Save kien-hoang/74930e56a7867e5940a9bc9077af2e7a to your computer and use it in GitHub Desktop.
Observer Pattern in Swift
/*
Observer Pattern
1. The subscriber is the "observer" object and receives updates. `AppCoordinator`
2. The publisher is the "observable" object and sends updates. `LoginViewController`
3. The value is the underlying object that's changed.
*/
import UIKit
final class AppCoordinator {
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(loginSuccess),
name: Notification.Name("LoginSuccessNotification"),
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func loginSuccess() {
// Change root view here
print("Change root view to Home screen for example")
}
}
final class LoginViewController {
func login() {
// Call login API
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// Login Success
NotificationCenter.default.post(name: Notification.Name("LoginSuccessNotification"),
object: nil)
}
}
}
let appCoordinator = AppCoordinator()
let loginView = LoginViewController()
loginView.login()
/*
Change root view to Home screen for example
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment