Add dummy Listener without assigned bus

Thanks to that we can store Listener without ASAP initialization with bus
This commit is contained in:
Dawid Drozd 2019-09-14 14:59:40 +02:00
parent 48306cfc96
commit caa2b3e9ff

View File

@ -11,7 +11,9 @@ template <class Bus>
class Listener class Listener
{ {
public: public:
Listener(Bus& bus) explicit Listener() = default; // Dummy listener
explicit Listener(Bus& bus)
: _id{bus.newListenerID()} : _id{bus.newListenerID()}
, _bus{&bus} , _bus{&bus}
{} {}
@ -43,8 +45,10 @@ public:
return *this; return *this;
} }
unlistenAll(); if(_bus != nullptr)
{
unlistenAll();
}
_id = other._id; _id = other._id;
other._id = 0; other._id = 0;
_bus = other._bus; _bus = other._bus;
@ -56,6 +60,10 @@ public:
template <class Event> template <class Event>
void listen(std::function<void(const Event&)>&& callback) void listen(std::function<void(const Event&)>&& callback)
{ {
if(_bus == nullptr)
{
throw std::runtime_error{"bus is null"};
}
_bus->template listen<Event>(_id, _bus->template listen<Event>(_id,
std::forward<std::function<void(const Event&)>>(callback)); std::forward<std::function<void(const Event&)>>(callback));
} }
@ -63,24 +71,35 @@ public:
template <class Event> template <class Event>
void listen(const std::function<void(const Event&)>& callback) void listen(const std::function<void(const Event&)>& callback)
{ {
if(_bus == nullptr)
{
throw std::runtime_error{"bus is null"};
}
_bus->template listen<Event>(_id, callback); _bus->template listen<Event>(_id, callback);
} }
void unlistenAll() void unlistenAll()
{ {
if(_bus == nullptr)
{
throw std::runtime_error{"bus is null"};
}
_bus->unlistenAll(_id); _bus->unlistenAll(_id);
} }
template <typename Event> template <typename Event>
void unlisten() void unlisten()
{ {
if(_bus == nullptr)
{
throw std::runtime_error{"bus is null"};
}
_bus->template unlisten<Event>(_id); _bus->template unlisten<Event>(_id);
} }
private: private:
std::uint32_t _id = 0; std::uint32_t _id = 0;
Bus* _bus; Bus* _bus = nullptr;
}; };
} // namespace dexode::eventbus } // namespace dexode::eventbus