Files
spark/src/lib/orderman/orderman_utils/EventStream.h
T

76 lines
1.5 KiB
C++

#pragma once
#include <algorithm>
#include <boost/container/small_vector.hpp>
#include "lib/mercury/actors/ContentSubscription.h"
namespace bts {
namespace orderman {
template <class EV, class K = mercury::KeyExtractor>
struct EventStream
{
using CS = mercury::ContentSubscription<EV,K>;
using SubID = typename CS::SubID;
EventStream () : cs (nullptr) {}
EventStream (CS&cs) : cs (&cs) {}
void init(CS&csub)
{
cs = &csub;
}
template <class CB>
SubID sub(typename CS::Key k, CB&&cb) {
auto s = cs->sub(k,std::forward<CB> (cb));
active_subs.push_back(s);
return s;
}
template <class CB>
SubID sub(CB&&cb) {
auto s = cs->sub(std::forward<CB> (cb));
active_subs.push_back(s);
return s;
}
EventStream& operator=(EventStream &&src)
{
cs = src.cs;
src.cs = nullptr;
active_subs = src.active_subs;
src.active_subs.clear();
return *this;
}
EventStream& operator=(EventStream const &src)
{
cs = src.cs;
active_subs = src.active_subs;
return *this;
}
void unsub(SubID sid) {
auto it = std::find(active_subs.begin(), active_subs.end(),sid);
if (it != active_subs.end()) {
active_subs.erase(it);
cs->unsub(sid);
}
}
void unsub_all() {
while (active_subs.size()) unsub(active_subs.front());
}
~EventStream() {
unsub_all();
}
private:
CS *cs;
boost::container::small_vector<SubID,10> active_subs;
};
}}