#pragma once #include #include #include #include #include namespace Void::Observable { // ── Handle — opaque subscription identifier ─────────────────────────────────── struct Handle { std::uint64_t id{0}; [[nodiscard]] bool valid() const noexcept { return id != 0; } [[nodiscard]] bool operator==(const Handle&) const noexcept = default; }; // ── Observable ───────────────────────────────────────────────────────────── // A value that observers can subscribe to via on_change(). // Observers receive (old_value, new_value) on every set() call that changes // the stored value. template class Observable { public: using Listener = std::function; explicit Observable(T initial = {}) : value_{std::move(initial)} {} [[nodiscard]] const T& get() const noexcept { return value_; } [[nodiscard]] operator const T&() const noexcept { return value_; } void set(T new_val) { if (new_val == value_) return; T old = std::move(value_); value_ = std::move(new_val); notify(old, value_); } Observable& operator=(T new_val) { set(std::move(new_val)); return *this; } Handle on_change(Listener listener) { const Handle h{++next_id_}; listeners_.push_back({h, std::move(listener)}); return h; } bool unsubscribe(Handle h) { const auto it = std::ranges::find_if(listeners_, [&](const auto& e) { return e.h == h; }); if (it == listeners_.end()) return false; listeners_.erase(it); return true; } [[nodiscard]] std::size_t listener_count() const noexcept { return listeners_.size(); } private: void notify(const T& old_val, const T& new_val) { for (auto& [h, fn] : listeners_) fn(old_val, new_val); } T value_; std::uint64_t next_id_{0}; struct Entry { Handle h; Listener fn; }; std::vector listeners_; }; // ── Signal ─────────────────────────────────────────────────────────── // An event signal that observers connect to. emit() calls all connected slots. template class Signal { public: using Slot = std::function; Handle connect(Slot slot) { const Handle h{++next_id_}; slots_.push_back({h, std::move(slot)}); return h; } bool disconnect(Handle h) { const auto it = std::ranges::find_if(slots_, [&](const auto& e) { return e.h == h; }); if (it == slots_.end()) return false; slots_.erase(it); return true; } void emit(const Args&... args) const { for (const auto& [h, fn] : slots_) fn(args...); } [[nodiscard]] std::size_t slot_count() const noexcept { return slots_.size(); } void clear() noexcept { slots_.clear(); } private: std::uint64_t next_id_{0}; struct Entry { Handle h; Slot fn; }; std::vector slots_; }; } // namespace Void::Observable