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
|
|
|
|
{
|
|
|
|
|
2016-11-14 09:24:40 +01:00
|
|
|
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);
|
2016-11-14 09:24:40 +01:00
|
|
|
EventCollector(EventCollector const& other);
|
|
|
|
EventCollector(EventCollector&& other);
|
2016-10-18 21:48:44 +02:00
|
|
|
|
2016-11-14 09:24:40 +01: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
|
|
|
*
|
2017-08-26 13:28:45 +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
|
|
|
*/
|
2017-08-26 13:28:45 +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)
|
2016-11-14 09:24:40 +01:00
|
|
|
{
|
|
|
|
return;//Skip such things
|
|
|
|
}
|
2016-10-18 21:48:44 +02:00
|
|
|
if (_token == 0)
|
|
|
|
{
|
2017-08-26 13:28:45 +02:00
|
|
|
_token = _bus->listen<Event>(callback);
|
2016-10-18 21:48:44 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2017-08-26 13:28:45 +02:00
|
|
|
_bus->listen<Event>(_token, callback);
|
2016-10-18 21:48:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void unlistenAll();
|
|
|
|
|
|
|
|
/**
|
2017-08-26 13:28:45 +02:00
|
|
|
* @tparam Event - type you want to unlisten. @see Notiier::listen
|
2016-10-18 21:48:44 +02:00
|
|
|
*/
|
2017-08-26 13:28:45 +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
|
|
|
{
|
2017-08-26 13:28:45 +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
|
|
|
};
|
|
|
|
|
|
|
|
}
|