EventBus/include/eventbus/EventCollector.h

106 lines
1.9 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
{
2017-12-04 13:24:44 +01:00
class [[deprecated("This class will be removed, is breaking API")]] BusAttorney
{
public:
BusAttorney(std::shared_ptr<EventBus> bus)
: _bus(std::move(bus))
{
}
/**
* Notify all listeners for event
*
* @param event your event struct
*/
template<typename Event>
2017-12-04 13:24:44 +01:00
[[deprecated]]
2017-11-24 12:54:17 +01:00
void notify(const Event& event) const
{
_bus->notify(event);
}
2017-12-04 13:24:44 +01:00
[[deprecated]]
std::shared_ptr<EventBus> extract() const
2017-11-24 12:54:17 +01:00
{
return _bus;
}
private:
std::shared_ptr<EventBus> _bus;
};
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
}
bool isUsing(const std::shared_ptr<EventBus>& bus) const;
///I wan't explicitly say getBus. Ok we could add method for notify but this is more explicit
2017-12-04 13:24:44 +01:00
[[deprecated("This method will be removed, is breaking encapsulation")]]
BusAttorney getBus() const;
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
};
}