Add EventContainer for RAII

This commit is contained in:
Dawid Drozd 2016-10-18 21:48:44 +02:00
parent e23c3b2850
commit d44c38d24e
2 changed files with 98 additions and 0 deletions

40
src/EventContainer.cpp Normal file
View File

@ -0,0 +1,40 @@
//
// Created by Dawid Drozd aka Gelldur on 18/10/16.
//
#include "EventContainer.h"
namespace Dexode
{
EventContainer::EventContainer(const std::shared_ptr<Notifier>& notifier)
: _notifier(notifier)
{
assert(_notifier);
}
void null_deleter(Notifier*)
{
}
//Maybe ugly but hey ;) Less code and simply i can :D
EventContainer::EventContainer(Notifier& notifier)
: _notifier(&notifier, &null_deleter)
{
assert(_notifier);
}
EventContainer::~EventContainer()
{
unlistenAll();
}
void EventContainer::unlistenAll()
{
if (_token != 0)
{
_notifier->unlistenAll(_token);
}
}
}

58
src/EventContainer.h Normal file
View File

@ -0,0 +1,58 @@
//
// Created by Dawid Drozd aka Gelldur on 18/10/16.
//
#pragma once
#include <memory>
#include "Notifier.h"
namespace Dexode
{
class EventContainer
{
public:
EventContainer(const std::shared_ptr<Notifier>& notifier);
EventContainer(Notifier& notifier = Notifier::getGlobal());
~EventContainer();
/**
* Register listener for notification. Returns token used to unregister
*
* @param notification - pass notification like "getNotificationXYZ()"
* @param callback - your callback to handle notification
*/
template<typename ... Args>
void listen(const Notification<Args...>& notification
, typename notifier_traits<const std::function<void(Args...)>&>::type callback)
{
if (_token == 0)
{
_token = _notifier->listen(notification, callback);
}
else
{
_notifier->listen(_token, notification, callback);
}
}
void unlistenAll();
/**
* @param notification - notification you wan't to unlisten. @see Notiier::listen
*/
template<typename NotificationType, typename ... Args>
void unlisten(const NotificationType& notification)
{
_notifier->unlisten(_token, notification);
}
private:
int _token = 0;
std::shared_ptr<Notifier> _notifier;
};
}