Last active
August 2, 2018 14:47
-
-
Save V8tr/3edc83fa1a457a9f6bb54cb1b0f9d2b7 to your computer and use it in GitHub Desktop.
Refactoring Massive App Delegate using Mediator pattern. See blog post for more details: https://www.vadimbulavin.com/refactoring-massive-app-delegate
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
// MARK: - AppLifecycleListener | |
protocol AppLifecycleListener { | |
func onAppWillEnterForeground() | |
func onAppDidEnterBackground() | |
func onAppDidFinishLaunching() | |
} | |
// MARK: - Mediator | |
class AppLifecycleMediator: NSObject { | |
private let listeners: [AppLifecycleListener] | |
init(listeners: [AppLifecycleListener]) { | |
self.listeners = listeners | |
super.init() | |
subscribe() | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self) | |
} | |
private func subscribe() { | |
NotificationCenter.default.addObserver(self, selector: #selector(onAppWillEnterForeground), name: .UIApplicationWillEnterForeground, object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(onAppDidEnterBackground), name: .UIApplicationDidEnterBackground, object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(onAppDidFinishLaunching), name: .UIApplicationDidFinishLaunching, object: nil) | |
} | |
@objc private func onAppWillEnterForeground() { | |
listeners.forEach { $0.onAppWillEnterForeground() } | |
} | |
@objc private func onAppDidEnterBackground() { | |
listeners.forEach { $0.onAppDidEnterBackground() } | |
} | |
@objc private func onAppDidFinishLaunching() { | |
listeners.forEach { $0.onAppDidFinishLaunching() } | |
} | |
} | |
extension AppLifecycleMediator { | |
static func makeDefaultMediator() -> AppLifecycleMediator { | |
let listener1 = ... | |
let listener2 = ... | |
return AppLifecycleMediator(listeners: [listener1, listener2]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment