28#include <unordered_map>
37 std::ostringstream oss;
44ListenersByKey& ListenersByKey::GetInstance(
const std::string& key) {
45 static std::unordered_map<std::string, ListenersByKey> instances;
46 static std::mutex s_mutex;
48 std::lock_guard<std::mutex> lock(s_mutex);
49 if (instances.find(key) == instances.end()) {
50 instances[key] = ListenersByKey();
52 return instances[key];
57using EvPair = std::pair<wxEvtHandler*, wxEventType>;
59void Observable::Listen(wxEvtHandler* listener, wxEventType ev_type) {
60 std::lock_guard<std::mutex> lock(m_mutex);
61 const auto& listeners = m_list.listeners;
63 EvPair key_pair(listener, ev_type);
64 auto found = std::find(listeners.begin(), listeners.end(), key_pair);
65 assert((found == listeners.end()) &&
"Duplicate listener");
66 m_list.listeners.push_back(key_pair);
70 std::lock_guard<std::mutex> lock(m_mutex);
71 auto& listeners = m_list.listeners;
73 EvPair key_pair(listener, ev_type);
74 auto found = std::find(listeners.begin(), listeners.end(), key_pair);
75 if (found == listeners.end())
return false;
76 listeners.erase(found);
81 const std::string& s,
int num,
void* client_data) {
82 std::lock_guard<std::mutex> lock(m_mutex);
83 auto& listeners = m_list.listeners;
85 for (
const auto& l : listeners) {
87 evt->SetSharedPtr(ptr);
88 evt->SetClientData(client_data);
89 evt->SetString(s.c_str());
91 wxQueueEvent(l.first, evt);
102 if (!m_key.empty()) Unlisten();
109void ObservableListener::Listen() {
110 if (!m_key.empty()) {
116void ObservableListener::Unlisten() {
117 if (!m_key.empty()) {
void Listen(const std::string &key, wxEvtHandler *listener, wxEventType evt)
Set object to send wxEventType ev to listeners on changes in key.
Custom event class for OpenCPN's notification system.
The observable notify/listen basic nuts and bolts.
virtual void Notify()
Notify all listeners to configured key about variable change.
bool Unlisten(wxEvtHandler *listener, wxEventType ev)
Remove window listening to ev from list of listeners.
General observable pattern implementation built on top of wxWidgets event handling.
std::string PtrKey(const void *ptr)
Return address as printable string.