Toast Engine
Loading...
Searching...
No Matches
listener.inl
1#pragma once
2#include "listener.hpp"
3#include "toast/log.hpp"
4
5#include <utility>
6
7namespace event {
8
9template<typename TEvent>
10void Listener::unsubscribe(std::string_view name) noexcept {
11 TOAST_TRACE("Events", "Unsubscribing Callback {} to {}", name, typeid(TEvent).name());
12 std::erase_if(m.callbacks, [&](auto& callback) {
13 auto& [type, sub_name, any] = callback;
14 if (typeid(TEvent) == type && name == sub_name) {
15 auto any_val = std::any_cast<typename Event<TEvent>::iterator_t>(any);
16 Event<TEvent>::unsubscribe(any_val);
17 return true;
18 }
19 return false;
20 });
21}
22
23template<typename TEvent, EventCallback<TEvent&> F>
24void Listener::subscribe(std::string name, F&& callback, char priority) noexcept {
25 TOAST_TRACE("Events", "Subscribing Callback {} to {}", name, typeid(TEvent).name());
26 auto wrapper = [fn = std::forward<F>(callback), enabled = m.enabled](TEvent& e) mutable -> bool {
27 if (not enabled->load()) {
28 return false;
29 }
30 if constexpr (std::is_invocable_r_v<bool, F, TEvent&>) { // Returns bool(T&)
31 return std::invoke(fn, e);
32 } else if constexpr (std::is_invocable_v<F, TEvent&>) { // Returns void(T&)
33 std::invoke(fn, e);
34 return false;
35 } else if constexpr (std::is_invocable_r_v<bool, F>) { // Returns bool()
36 return std::invoke(fn);
37 } else { // Returns void()
38 std::invoke(fn);
39 return false;
40 }
41 };
42
43 auto it = Event<TEvent>::subscribe(priority, std::move(wrapper));
44 m.callbacks.push_back({typeid(TEvent), std::move(name), it});
45}
46
47template<typename TEvent, EventCallback<TEvent&> F>
48void Listener::subscribe(F&& callback, char priority) noexcept {
49 subscribe<TEvent>("unnamed", std::forward<F>(callback), priority);
50}
51
52}
void unsubscribe(std::string_view name) noexcept
unsubscribes every event in type TEvent with that name
Definition listener.inl:10
void subscribe(std::string name, F &&callback, char priority=0) noexcept
subscribes a callback to an TEvent
Definition listener.inl:24
Public logging interface for the engine.
#define TOAST_TRACE(sink,...)
Writes a message to the log console.
Definition log.hpp:71