Doxygen with github
Loading...
Searching...
No Matches
ksEvent.h
1/*
2 * Copyright (c) 2021-2023, Krzysztof Strehlau
3 *
4 * This file is a part of the ksIotFramework 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 <memory>
14#include <functional>
15
16#include "ksEventInterface.h"
17#include "ksEventHandle.h"
18
24#define DECLARE_KS_EVENT(evtName, ...) \
25 std::shared_ptr<ksf::evt::ksEvent<__VA_ARGS__>> evtName {std::make_shared<ksf::evt::ksEvent<__VA_ARGS__>>()};
26
27namespace ksf::evt
28{
33 template <typename... Params>
35 {
36 protected:
37 std::vector<std::pair<std::size_t, std::function<void(Params...)>>> callbacks;
38 std::size_t lastCallbackUID{0};
39
40 public:
45 bool isBound() const
46 {
47 return !callbacks.empty();
48 }
49
55 void registerEvent(std::unique_ptr<ksf::evt::ksEventHandle>& outHandle, std::function<void(Params...)>&& function)
56 {
58 outHandle = std::make_unique<ksf::evt::ksEventHandle>(weak_from_this(), lastCallbackUID);
59 callbacks.emplace_back(lastCallbackUID, std::move(function));
60 }
61
70 void unbind(std::size_t callbackUID) override
71 {
72 auto predicate = [callbackUID](const auto& cb) {
73 auto& [uid, function] = cb;
74 return uid == callbackUID;
75 };
76
77 callbacks.erase(std::remove_if(callbacks.begin(), callbacks.end(), predicate), callbacks.end());
78 }
79
84 void broadcast(Params... params)
85 {
86 for (const auto& [uid, function] : callbacks)
87 function(params...);
88 }
89 };
90}
Base class for multicasting events.
Definition ksEvent.h:35
void registerEvent(std::unique_ptr< ksf::evt::ksEventHandle > &outHandle, std::function< void(Params...)> &&function)
Registers event (binds to callback list).
Definition ksEvent.h:55
std::vector< std::pair< std::size_t, std::function< void(Params...)> > > callbacks
List of bond callbacks.
Definition ksEvent.h:37
void unbind(std::size_t callbackUID) override
Unbinds event callback by specified unique ID.
Definition ksEvent.h:70
std::size_t lastCallbackUID
Last unique callback ID for this event (used as counter).
Definition ksEvent.h:38
bool isBound() const
Returns whether any callback is bound to this event.
Definition ksEvent.h:45
void broadcast(Params... params)
Broadcasts event to all bound callbacks.
Definition ksEvent.h:84
Implements interface for multicasting events.
Definition ksEventInterface.h:20