Created
February 1, 2023 11:04
-
-
Save kien-hoang/74930e56a7867e5940a9bc9077af2e7a to your computer and use it in GitHub Desktop.
Observer Pattern in Swift
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
/* | |
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