17 #ifndef KAA_OBSERVER_KAAOBSERVABLE_HPP_
18 #define KAA_OBSERVER_KAAOBSERVABLE_HPP_
21 #include <unordered_map>
22 #include <unordered_set>
29 template<
class Signature,
class Key,
class Function = std::function<Signature>>
40 auto it = slots_.find(key);
41 if (it != slots_.end() && !it->second.isRemoved()) {
44 slotsToRemove_.erase(key);
45 slotsToAdd_.insert(std::make_pair(key, CallbackWrapper(f)));
49 return slots_.insert(std::make_pair(key, CallbackWrapper(f))).second;
57 slotsToAdd_.erase(key);
58 slotsToRemove_.insert(key);
60 auto it = slots_.find(key);
61 if (it != slots_.end()) {
70 template <
typename... Args>
75 for (
auto& pair : slots_) {
81 for (
auto it = slotsToAdd_.begin(); it != slotsToAdd_.end(); ++it) {
82 slots_[it->first] = it->second;
86 for (
auto key : slotsToRemove_) {
89 slotsToRemove_.clear();
96 CallbackWrapper() : isRemoved_(false) { }
97 CallbackWrapper(
const Function& f) : callback_(f), isRemoved_(false) { }
98 CallbackWrapper(
const CallbackWrapper& o) : callback_(o.callback_), isRemoved_((bool) o.isRemoved_) { }
99 CallbackWrapper& operator=(
const CallbackWrapper& o) { callback_ = o.callback_; isRemoved_ = (bool) o.isRemoved_;
return *
this; }
101 template <
typename... Args>
109 bool isRemoved()
const {
return isRemoved_; }
110 void remove() { isRemoved_ =
true; }
117 std::unordered_map<Key, CallbackWrapper> slots_;
118 std::unordered_map<Key, CallbackWrapper> slotsToAdd_;
119 std::unordered_set<Key> slotsToRemove_;
123 KAA_MUTEX_DECLARE(mainGuard_);
124 KAA_MUTEX_DECLARE(modificationGuard_);
void removeCallback(const Key &key)
#define KAA_MUTEX_UNIQUE_DECLARE(name, mtx)
void operator()(Args &...args)
bool addCallback(const Key &key, const Function &f)