Doxygen with github
Loading...
Searching...
No Matches
ksEvent.h
1/*
2 * Copyright (c) 2020-2026, Krzysztof Strehlau
3 *
4 * This file is a part of the ksIotFrameworkLib IoT library.
5 * All licensing information can be found inside LICENSE.md file.
6 *
7 * https://github.com/cziter15/ksIotFrameworkLib/blob/master/LICENSE
8 */
9
10#pragma once
11
12#include <vector>
13#include <algorithm>
14#include <memory>
15#include <functional>
16
17#include "ksEventInterface.h"
18#include "ksEventHandle.h"
19
25#define DECLARE_KS_EVENT(evtName, ...) \
26 std::shared_ptr<ksf::evt::ksEvent<__VA_ARGS__>> evtName {std::make_shared<ksf::evt::ksEvent<__VA_ARGS__>>()};
27
28namespace ksf::evt
29{
34 template <typename... Params>
36 {
37 protected:
38 std::vector<std::pair<std::size_t, std::function<void(Params...)>>> callbacks;
39 std::size_t lastCallbackUID{0};
40
41 public:
46 bool isBound() const
47 {
48 return !callbacks.empty();
49 }
50
56 void registerEvent(std::unique_ptr<ksf::evt::ksEventHandle>& outHandle, std::function<void(Params...)>&& function)
57 {
59 outHandle = std::make_unique<ksf::evt::ksEventHandle>(weak_from_this(), lastCallbackUID);
60 callbacks.emplace_back(lastCallbackUID, std::move(function));
61 }
62
71 void unbind(std::size_t callbackUID) override
72 {
73 auto predicate = [callbackUID](const auto& cb) {
74 auto& [uid, function] = cb;
75 return uid == callbackUID;
76 };
77
78 callbacks.erase(std::remove_if(callbacks.begin(), callbacks.end(), predicate), callbacks.end());
79 }
80
85 void broadcast(Params... params) const
86 {
87 for (const auto& [uid, function] : callbacks)
88 function(params...);
89 }
90 };
91}
Base class for multicasting events.
Definition ksEvent.h:36
void registerEvent(std::unique_ptr< ksf::evt::ksEventHandle > &outHandle, std::function< void(Params...)> &&function)
Registers event (binds to callback list).
Definition ksEvent.h:56
std::vector< std::pair< std::size_t, std::function< void(Params...)> > > callbacks
List of bond callbacks.
Definition ksEvent.h:38
void unbind(std::size_t callbackUID) override
Unbinds event callback by specified unique ID.
Definition ksEvent.h:71
std::size_t lastCallbackUID
Last unique callback ID for this event (used as counter).
Definition ksEvent.h:39
bool isBound() const
Returns whether any callback is bound to this event.
Definition ksEvent.h:46
void broadcast(Params... params) const
Broadcasts event to all bound callbacks.
Definition ksEvent.h:85
Implements interface for multicasting events.
Definition ksEventInterface.h:21