5#ifndef MOLYBDEN_EVENT_IMPL_HPP
6#define MOLYBDEN_EVENT_IMPL_HPP
10#include <unordered_map>
12#include "molybden/base/internal/subscription_impl.hpp"
14namespace molybden::internal {
17class EventImpl : SubscriptionObserver {
19 ~EventImpl()
override;
21 using Signature = void(
const T& e);
23 std::shared_ptr<Subscription> operator+=(std::function<Signature> observer);
25 void notify(
const T& args);
30 void onCanceled(int32_t
id)
override;
32 std::vector<std::shared_ptr<SubscriptionImpl<T>>> subscriptions();
34 std::recursive_mutex subscriptions_mutex_;
35 std::unordered_map<int32_t, std::shared_ptr<SubscriptionImpl<T>>>
40std::vector<std::shared_ptr<SubscriptionImpl<T>>>
41EventImpl<T>::subscriptions() {
42 std::lock_guard guard(subscriptions_mutex_);
43 std::vector<std::shared_ptr<SubscriptionImpl<T>>> subscriptions;
44 for (
auto it : subscriptions_) {
45 subscriptions.push_back(it.second);
51EventImpl<T>::~EventImpl() {
52 for (
auto subscription : subscriptions()) {
53 subscription->setObserver(
nullptr);
58std::shared_ptr<Subscription> EventImpl<T>::operator+=(
59 std::function<Signature> observer) {
60 static std::atomic next_id(0);
61 int32_t
id = ++next_id;
62 auto subscription = std::make_shared<SubscriptionImpl<T>>(id, observer);
63 subscription->setObserver(
this);
65 std::lock_guard guard(subscriptions_mutex_);
66 subscriptions_.emplace(
id, subscription);
72void EventImpl<T>::notify(
const T& args) {
73 std::lock_guard guard(subscriptions_mutex_);
74 for (
auto subscription : subscriptions()) {
75 subscription->notify(args);
80void EventImpl<T>::reset() {
81 std::lock_guard guard(subscriptions_mutex_);
82 subscriptions_.clear();
86void EventImpl<T>::onCanceled(int32_t
id) {
87 std::lock_guard guard(subscriptions_mutex_);
88 subscriptions_.erase(
id);