xbmc
EventStreamDetail.h
1 /*
2  * Copyright (C) 2016-2018 Team Kodi
3  * This file is part of Kodi - https://kodi.tv
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  * See LICENSES/README.md for more information.
7  */
8 
9 #pragma once
10 
11 #include "threads/CriticalSection.h"
12 
13 #include <mutex>
14 
15 namespace detail
16 {
17 
18 template<typename Event>
20 {
21 public:
22  virtual void HandleEvent(const Event& event) = 0;
23  virtual void Cancel() = 0;
24  virtual bool IsOwnedBy(void* obj) = 0;
25  virtual ~ISubscription() = default;
26 };
27 
28 template<typename Event, typename Owner>
29 class CSubscription : public ISubscription<Event>
30 {
31 public:
32  typedef void (Owner::*Fn)(const Event&);
33  CSubscription(Owner* owner, Fn fn);
34  void HandleEvent(const Event& event) override;
35  void Cancel() override;
36  bool IsOwnedBy(void *obj) override;
37 
38 private:
39  Owner* m_owner;
40  Fn m_eventHandler;
41  CCriticalSection m_criticalSection;
42 };
43 
44 template<typename Event, typename Owner>
46  : m_owner(owner), m_eventHandler(fn)
47 {}
48 
49 template<typename Event, typename Owner>
51 {
52  std::unique_lock<CCriticalSection> lock(m_criticalSection);
53  return obj != nullptr && obj == m_owner;
54 }
55 
56 template<typename Event, typename Owner>
58 {
59  std::unique_lock<CCriticalSection> lock(m_criticalSection);
60  m_owner = nullptr;
61 }
62 
63 template<typename Event, typename Owner>
64 void CSubscription<Event, Owner>::HandleEvent(const Event& event)
65 {
66  std::unique_lock<CCriticalSection> lock(m_criticalSection);
67  if (m_owner)
68  (m_owner->*m_eventHandler)(event);
69 }
70 }
Definition: EventStreamDetail.h:29
Definition: EventStreamDetail.h:15
Definition: EventStreamDetail.h:19