5#ifndef MOLYBDEN_EVENT_IMPL_HPP
6#define MOLYBDEN_EVENT_IMPL_HPP
10#include <unordered_map>
12#include "molybden/base/internal/subscription_impl.hpp"
18class EventImpl : SubscriptionObserver {
20 ~EventImpl()
override;
22 using Signature = void(
const T& e);
24 std::shared_ptr<Subscription> operator+=(std::function<Signature> observer);
26 void notify(
const T& args);
31 void onCanceled(int32_t
id)
override;
33 std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>> subscriptions();
35 std::mutex subscriptions_mutex_;
36 std::unordered_map<int32_t, std::shared_ptr<internal::SubscriptionImpl<T>>>
41std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>>
42EventImpl<T>::subscriptions() {
43 std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>> subscriptions;
44 for (
auto it : subscriptions_) {
45 subscriptions.push_back(it.second);
51EventImpl<T>::~EventImpl() {
52 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
53 for (
auto subscription : subscriptions()) {
54 subscription->setObserver(
nullptr);
59std::shared_ptr<Subscription> EventImpl<T>::operator+=(
60 std::function<Signature> observer) {
61 static std::atomic<int32_t> next_id(0);
62 int32_t
id = ++next_id;
63 auto subscription = std::make_shared<internal::SubscriptionImpl<T>>(id,
65 subscription->setObserver(
this);
67 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
68 subscriptions_.emplace(
id, subscription);
74void EventImpl<T>::notify(
const T& args) {
75 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
76 for (
auto subscription : subscriptions()) {
77 subscription->notify(args);
82void EventImpl<T>::reset() {
83 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
84 subscriptions_.clear();
88void EventImpl<T>::onCanceled(int32_t
id) {
89 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
90 subscriptions_.erase(
id);