EventBus/include/eventbus/EventCollector.h

70 lines
1.1 KiB
C
Raw Normal View History

2016-10-18 21:48:44 +02:00
//
// Created by Dawid Drozd aka Gelldur on 18/10/16.
//
#pragma once
#include <memory>
2017-08-06 11:22:59 +02:00
#include "EventBus.h"
2016-10-18 21:48:44 +02:00
namespace Dexode
{
class EventCollector
2016-10-18 21:48:44 +02:00
{
public:
2017-08-06 17:24:13 +02:00
EventCollector(const std::shared_ptr<EventBus>& bus);
EventCollector(EventBus* bus);
EventCollector(EventCollector const& other);
EventCollector(EventCollector&& other);
2016-10-18 21:48:44 +02:00
~EventCollector();
EventCollector& operator=(EventCollector const& other);
EventCollector& operator=(EventCollector&& other);
2016-10-18 21:48:44 +02:00
/**
2017-08-06 17:24:13 +02:00
* Register listener for event.
2016-10-18 21:48:44 +02:00
*
* @tparam Event - type you want to listen for
2017-08-06 17:24:13 +02:00
* @param callback - your callback to handle event
2016-10-18 21:48:44 +02:00
*/
template<typename Event>
void listen(const std::function<void(const Event&)>& callback)
2016-10-18 21:48:44 +02:00
{
2017-08-06 17:24:13 +02:00
if (!callback || !_bus)
{
return;//Skip such things
}
2016-10-18 21:48:44 +02:00
if (_token == 0)
{
_token = _bus->listen<Event>(callback);
2016-10-18 21:48:44 +02:00
}
else
{
_bus->listen<Event>(_token, callback);
2016-10-18 21:48:44 +02:00
}
}
void unlistenAll();
/**
* @tparam Event - type you want to unlisten. @see Notiier::listen
2016-10-18 21:48:44 +02:00
*/
template<typename Event>
void unlisten()
2016-10-18 21:48:44 +02:00
{
2017-08-06 17:24:13 +02:00
if (_bus)
2017-08-06 11:22:59 +02:00
{
_bus->unlisten<Event>(_token);
2017-08-06 11:22:59 +02:00
}
2016-10-18 21:48:44 +02:00
}
private:
int _token = 0;
2017-08-06 17:24:13 +02:00
std::shared_ptr<EventBus> _bus;
2016-10-18 21:48:44 +02:00
};
}