use vector for subscribers in event system

Summary:
Replaced global event subscriber with a vector of subscriber functions
Further changes in commit stack support the mutiple subscribers in event system

Reviewed By: davidaurelio

Differential Revision: D15352451

fbshipit-source-id: 7ca6f0943735bf1f76a906c23e15e14ae3c5f42c
This commit is contained in:
Sidharth Guglani
2019-05-15 08:57:50 -07:00
committed by Facebook Github Bot
parent cf809b8e8b
commit a9514513a7
2 changed files with 11 additions and 14 deletions

View File

@@ -15,31 +15,26 @@ namespace yoga {
namespace { namespace {
// For now, a single subscriber is enough. Event::Subscribers& eventSubscribers() {
// This can be changed as soon as the need for more than one subscriber arises. static Event::Subscribers subscribers = {};
std::function<Event::Subscriber>& globalEventSubscriber() { return subscribers;
static std::function<Event::Subscriber> subscriber = nullptr;
return subscriber;
} }
} // namespace } // namespace
void Event::reset() { void Event::reset() {
globalEventSubscriber() = nullptr; eventSubscribers() = {};
} }
void Event::subscribe(std::function<Subscriber>&& subscriber) { void Event::subscribe(std::function<Subscriber>&& subscriber) {
if (globalEventSubscriber() != nullptr) { eventSubscribers().push_back(subscriber);
throw std::logic_error(
"Yoga currently supports only one global event subscriber");
}
globalEventSubscriber() = std::move(subscriber);
} }
void Event::publish(const YGNode& node, Type eventType, const Data& eventData) { void Event::publish(const YGNode& node, Type eventType, const Data& eventData) {
auto& subscriber = globalEventSubscriber(); for (auto& subscriber : eventSubscribers()) {
if (subscriber) { if (subscriber) {
subscriber(node, eventType, eventData); subscriber(node, eventType, eventData);
}
} }
} }

View File

@@ -7,6 +7,7 @@
#pragma once #pragma once
#include <functional> #include <functional>
#include <vector>
struct YGConfig; struct YGConfig;
struct YGNode; struct YGNode;
@@ -24,6 +25,7 @@ struct Event {
}; };
class Data; class Data;
using Subscriber = void(const YGNode&, Type, Data); using Subscriber = void(const YGNode&, Type, Data);
using Subscribers = std::vector<std::function<Subscriber>>;
template <Type E> template <Type E>
struct TypedData {}; struct TypedData {};