I'm actually trying to implement a pub/sub pattern into my Swift projects, I have few Agents (Singleton
s) that perform tasks, when their status change they should notify all the listener previously subscribed.
I get the error shaping my protocol, probably it should be conforming to the Equatable
protocol, but I cannot see in which way (declaring protocol AvailableChatListener: Equatable
resolves nothing).
I know that I could use the Apple's NSNotificationCenter
(as nicely points here), but it's not a solution completely suitable for my requirements.
Here the code:
AvailableChatListener.swift
protocol AvailableChatListener {
func onAvailableChatChange()
}
AvailableChatAgent.swift
class AvailableChatAgent {
// MARK: - Singleton
class var sharedInstance: AvailableChatAgent {
struct Singleton {
static let instance = AvailableChatAgent()
}
return Singleton.instance
}
// MARK: - Listeners
private var availableChatListeners = [AvailableChatListener]()
// MARK: - Public Properties
// current Chats
var currentChats = [Chat]() {
didSet {
statusChanged()
}
}
func startObserving() {
// ...
// perform tasks and change currentChats
// ...
}
func stopObserving() {
// ...
// stop tasks
// ...
}
func statusChanged() {
// notify listeners
for receiver in availableChatListeners {
receiver.onAvailableChatChange()
}
}
// ERROR #1
func subscribeListener(listener: AvailableChatListener) {
availableChatListeners.append(listener)
}
// ERROR #1
func unsubscribeListener(listener: AvailableChatListener) {
// ERROR #2
if let index = availableChatListeners.indexOf(listener) {
availableChatListeners.removeAtIndex(availableChatListeners.indexOf(listener)!)
if availableChatListeners.count == 0 {
self.stopObserving()
}
}
}
}
And here where I use this logic (for example in a TableViewController)
ChatListTableViewController.swift
class ChatListTableViewController: UITableViewController, AvailableChatListener {
// MARK: - Properties
var availableChatAgent = AvailableChatAgent.sharedInstance
// MARK: - ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
availableChatAgent.subscribeListener(self)
}
// MARK: - Implement AvailableChatListener
func onAvailableChatChange() {
// perform task with the new data, for example update UI
}
}
Thanks in advance.
UPDATE 1
Errors that I get:
protocol "AvailableChatListener' can only be used as a generic constraint because it has Self or associated type requirements
Cannot convert value of type 'AvailableChatListener' to expect argument type '@noescpae(AvailableChatListener) throws -> Bool'