6 #ifndef KAGOME_SUBSCRIPTION_ENGINE_HPP 7 #define KAGOME_SUBSCRIPTION_ENGINE_HPP 11 #include <shared_mutex> 12 #include <unordered_map> 16 template <
typename Event,
typename Receiver,
typename... Arguments>
29 template <
typename EventKey,
typename Receiver,
typename... EventParams>
31 :
public std::enable_shared_from_this<
32 SubscriptionEngine<EventKey, Receiver, EventParams...>> {
45 std::list<std::pair<SubscriptionSetId, SubscriberWeakPtr>>;
59 template <
typename KeyType,
typename ValueType,
typename... Args>
62 std::unordered_map<EventKeyType, SubscribersContainer>;
68 const EventKeyType &key,
70 std::unique_lock lock(subscribers_map_cs_);
71 auto &subscribers_list = subscribers_map_[key];
72 return subscribers_list.emplace(subscribers_list.end(),
73 std::make_pair(set_id, std::move(ptr)));
77 std::unique_lock lock(subscribers_map_cs_);
78 auto it = subscribers_map_.find(key);
79 if (subscribers_map_.end() != it) {
80 it->second.erase(it_remove);
81 if (it->second.empty()) subscribers_map_.erase(it);
86 size_t size(
const EventKeyType &key)
const {
87 std::shared_lock lock(subscribers_map_cs_);
88 if (
auto it = subscribers_map_.find(key); it != subscribers_map_.end())
89 return it->second.size();
95 std::shared_lock lock(subscribers_map_cs_);
97 for (
auto &it : subscribers_map_) count += it.second.size();
101 void notify(
const EventKeyType &key,
const EventParams &...args) {
102 std::shared_lock lock(subscribers_map_cs_);
103 auto it = subscribers_map_.find(key);
104 if (subscribers_map_.end() == it)
return;
106 auto &subscribers_container = it->second;
107 for (
auto it_sub = subscribers_container.begin();
108 it_sub != subscribers_container.end();) {
109 if (
auto sub = it_sub->second.lock()) {
110 sub->on_notify(it_sub->first, key, args...);
113 it_sub = subscribers_container.erase(it_sub);
121 #endif // KAGOME_SUBSCRIPTION_ENGINE_HPP KeyValueContainer subscribers_map_
void notify(const EventKeyType &key, const EventParams &...args)
std::list< std::pair< SubscriptionSetId, SubscriberWeakPtr >> SubscribersContainer
std::weak_ptr< SubscriberType > SubscriberWeakPtr
std::shared_mutex subscribers_map_cs_
IteratorType subscribe(SubscriptionSetId set_id, const EventKeyType &key, SubscriberWeakPtr ptr)
void unsubscribe(const EventKeyType &key, const IteratorType &it_remove)
size_t size(const EventKeyType &key) const
SubscriptionEngine()=default
~SubscriptionEngine()=default
SubscriptionEngine & operator=(SubscriptionEngine &&)=default
typename SubscribersContainer::iterator IteratorType
uint32_t SubscriptionSetId
std::unordered_map< EventKeyType, SubscribersContainer > KeyValueContainer