Merge pull request #26166 from ksooo/improve-plugin-ctx-menus
[xbmc.git] / xbmc / utils / Observer.cpp
blob5c60a4b7476ef62f7c56d2e6f999f8589b21465b
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
10 #include "Observer.h"
12 #include <algorithm>
13 #include <mutex>
15 Observable &Observable::operator=(const Observable &observable)
17 std::unique_lock<CCriticalSection> lock(m_obsCritSection);
19 m_bObservableChanged = static_cast<bool>(observable.m_bObservableChanged);
20 m_observers = observable.m_observers;
22 return *this;
25 bool Observable::IsObserving(const Observer &obs) const
27 std::unique_lock<CCriticalSection> lock(m_obsCritSection);
28 return std::find(m_observers.begin(), m_observers.end(), &obs) != m_observers.end();
31 void Observable::RegisterObserver(Observer *obs)
33 std::unique_lock<CCriticalSection> lock(m_obsCritSection);
34 if (!IsObserving(*obs))
36 m_observers.push_back(obs);
40 void Observable::UnregisterObserver(Observer *obs)
42 std::unique_lock<CCriticalSection> lock(m_obsCritSection);
43 auto iter = std::remove(m_observers.begin(), m_observers.end(), obs);
44 if (iter != m_observers.end())
45 m_observers.erase(iter);
48 void Observable::NotifyObservers(const ObservableMessage message /* = ObservableMessageNone */)
50 // Make sure the set/compare is atomic
51 // so we don't clobber the variable in a race condition
52 auto bNotify = m_bObservableChanged.exchange(false);
54 if (bNotify)
55 SendMessage(message);
58 void Observable::SetChanged(bool SetTo)
60 m_bObservableChanged = SetTo;
63 void Observable::SendMessage(const ObservableMessage message)
65 std::unique_lock<CCriticalSection> lock(m_obsCritSection);
67 for (auto& observer : m_observers)
69 observer->Notify(*this, message);