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);
29 void onCanceled(int32_t
id)
override;
31 std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>> subscriptions();
33 std::mutex subscriptions_mutex_;
34 std::unordered_map<int32_t, std::shared_ptr<internal::SubscriptionImpl<T>>>
39std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>>
40EventImpl<T>::subscriptions() {
41 std::vector<std::shared_ptr<internal::SubscriptionImpl<T>>> subscriptions;
42 for (
auto it : subscriptions_) {
43 subscriptions.push_back(it.second);
49EventImpl<T>::~EventImpl() {
50 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
51 for (
auto subscription : subscriptions()) {
52 subscription->setObserver(
nullptr);
57std::shared_ptr<Subscription> EventImpl<T>::operator+=(
58 std::function<Signature> observer) {
59 static std::atomic<int32_t> next_id(0);
60 int32_t
id = ++next_id;
61 auto subscription = std::make_shared<internal::SubscriptionImpl<T>>(id,
63 subscription->setObserver(
this);
65 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
66 subscriptions_.emplace(
id, subscription);
72void EventImpl<T>::notify(
const T& args) {
73 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
74 for (
auto subscription : subscriptions()) {
75 subscription->notify(args);
80void EventImpl<T>::onCanceled(int32_t
id) {
81 std::lock_guard<std::mutex> guard(subscriptions_mutex_);
82 subscriptions_.erase(
id);