carb/events/EventsUtils.h
File members: carb/events/EventsUtils.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Framework.h"
#include "../InterfaceUtils.h"
#include "../ObjectUtils.h"
#include "../dictionary/DictionaryUtils.h"
#include "IEvents.h"
#include <functional>
#include <utility>
namespace carb
{
namespace events
{
inline IEvents* getCachedEventsInterface()
{
return getCachedInterface<IEvents>();
}
class LambdaEventListener : public IEventListener
{
public:
LambdaEventListener(std::function<void(IEvent*)> fn) : m_fn(std::move(fn))
{
}
void onEvent(IEvent* e) override
{
if (m_fn)
m_fn(e);
}
private:
std::function<void(IEvent*)> m_fn;
CARB_IOBJECT_IMPL
};
inline ObjectPtr<ISubscription> createSubscriptionToPop(IEventStream* stream,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPop(
carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
inline ObjectPtr<ISubscription> createSubscriptionToPopByType(IEventStream* stream,
EventType eventType,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPopByType(
eventType, carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
inline ObjectPtr<ISubscription> createSubscriptionToPush(IEventStream* stream,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPush(
carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
inline ObjectPtr<ISubscription> createSubscriptionToPushByType(IEventStream* stream,
EventType eventType,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPushByType(
eventType, carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
} // namespace events
} // namespace carb