17 #ifndef KAA_OBSERVER_KAAOBSERVABLE_HPP_
18 #define KAA_OBSERVER_KAAOBSERVABLE_HPP_
21 #include <unordered_map>
22 #include <unordered_set>
31 template<
class Signature,
class Key,
class Function = std::function<Signature>>
44 auto it = slots_.find(key);
45 if (it != slots_.end() && !it->second.isRemoved()) {
48 slotsToRemove_.erase(key);
49 slotsToAdd_.insert(std::make_pair(key, CallbackWrapper(f)));
55 return slots_.insert(std::make_pair(key, CallbackWrapper(f))).second;
65 slotsToAdd_.erase(key);
66 slotsToRemove_.insert(key);
68 auto it = slots_.find(key);
69 if (it != slots_.end()) {
80 template <
typename... Args>
89 for (
auto& pair : slots_) {
91 pair.second(std::forward<Args>(args)...);
101 for (
auto it = slotsToAdd_.begin(); it != slotsToAdd_.end(); ++it) {
102 slots_[it->first] = it->second;
106 for (
auto key : slotsToRemove_) {
109 slotsToRemove_.clear();
122 return slots_.empty() && slotsToAdd_.empty();
126 class CallbackWrapper
129 CallbackWrapper() : isRemoved_(false) { }
130 CallbackWrapper(
const Function& f) : callback_(f), isRemoved_(false) { }
131 CallbackWrapper(
const CallbackWrapper& o) : callback_(o.callback_), isRemoved_((bool) o.isRemoved_) { }
132 CallbackWrapper(CallbackWrapper&& o) : callback_(std::move(o.callback_)), isRemoved_((bool) o.isRemoved_) { }
133 CallbackWrapper& operator=(
const CallbackWrapper& o) { callback_ = o.callback_; isRemoved_ = (bool) o.isRemoved_;
return *
this; }
134 CallbackWrapper& operator=(CallbackWrapper&& o) { callback_ = std::move(o.callback_); isRemoved_ = (bool) o.isRemoved_;
return *
this; }
136 template <
typename... Args>
140 callback_(std::forward<Args>(args)...);
144 bool isRemoved()
const {
return isRemoved_; }
145 void remove() { isRemoved_ =
true; }
152 std::unordered_map<Key, CallbackWrapper> slots_;
153 std::unordered_map<Key, CallbackWrapper> slotsToAdd_;
154 std::unordered_set<Key> slotsToRemove_;
158 KAA_MUTEX_DECLARE(mainGuard_);
159 KAA_MUTEX_DECLARE(modificationGuard_);
void operator()(Args &&...args)
std::atomic_bool bool_type
void removeCallback(const Key &key)
#define KAA_MUTEX_LOCKED(mutex_name)
#define KAA_MUTEX_UNIQUE_DECLARE(name, mtx)
bool addCallback(const Key &key, const Function &f)
#define KAA_MUTEX_LOCKING(mutex_name)