From be933ef2241d79558f91796cc5b3a161f72ebf9c Mon Sep 17 00:00:00 2001 From: manuel Date: Mon, 19 Oct 2020 00:52:24 +0200 Subject: sync with upstream --- xbmc/utils/EventStream.h | 100 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 xbmc/utils/EventStream.h (limited to 'xbmc/utils/EventStream.h') diff --git a/xbmc/utils/EventStream.h b/xbmc/utils/EventStream.h new file mode 100644 index 0000000..42a17df --- /dev/null +++ b/xbmc/utils/EventStream.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2016-2018 Team Kodi + * This file is part of Kodi - https://kodi.tv + * + * SPDX-License-Identifier: GPL-2.0-or-later + * See LICENSES/README.md for more information. + */ + +#pragma once + +#include "EventStreamDetail.h" +#include "JobManager.h" +#include "threads/CriticalSection.h" +#include "threads/SingleLock.h" + +#include +#include +#include + + +template +class CEventStream +{ +public: + + template + void Subscribe(A* owner, void (A::*fn)(const Event&)) + { + auto subscription = std::make_shared>(owner, fn); + CSingleLock lock(m_criticalSection); + m_subscriptions.emplace_back(std::move(subscription)); + } + + template + void Unsubscribe(A* obj) + { + std::vector>> toCancel; + { + CSingleLock lock(m_criticalSection); + auto it = m_subscriptions.begin(); + while (it != m_subscriptions.end()) + { + if ((*it)->IsOwnedBy(obj)) + { + toCancel.push_back(*it); + it = m_subscriptions.erase(it); + } + else + { + ++it; + } + } + } + for (auto& subscription : toCancel) + subscription->Cancel(); + } + +protected: + std::vector>> m_subscriptions; + CCriticalSection m_criticalSection; +}; + + +template +class CEventSource : public CEventStream +{ +public: + explicit CEventSource() : m_queue(false, 1, CJob::PRIORITY_HIGH) {}; + + template + void Publish(A event) + { + CSingleLock lock(this->m_criticalSection); + auto& subscriptions = this->m_subscriptions; + auto task = [subscriptions, event](){ + for (auto& s: subscriptions) + s->HandleEvent(event); + }; + lock.Leave(); + m_queue.Submit(std::move(task)); + } + +private: + CJobQueue m_queue; +}; + +template +class CBlockingEventSource : public CEventStream +{ +public: + template + void HandleEvent(A event) + { + CSingleLock lock(this->m_criticalSection); + for (const auto& subscription : this->m_subscriptions) + { + subscription->HandleEvent(event); + } + } +}; -- cgit v1.2.3