Files
spark/src/lib/api/public/Update.h
T
2017-08-07 17:21:12 -04:00

79 lines
2.7 KiB
C++

#pragma once
#include "RawUpdate.h"
#include <rxcpp/rx.hpp>
#include <functional>
#include <vector>
#include <unordered_map>
namespace bts {
namespace api {
template <typename T, typename TKey, typename ServiceType>
struct Update {
Update(std::vector<T>& all, std::vector<T>& added, std::vector<T>& removed) :
_all_items(std::move(all)),
_added_items(std::move(added)),
_removed_items(std::move(removed))
{}
Update(const Update& other) = delete;
Update(Update&& other) :
_all_items(std::move(other._all_items)),
_added_items(std::move(other._added_items)),
_removed_items(std::move(other._removed_items))
{}
TKey key(const T& t) const { return ServiceType::key(t); }
const std::vector<T>& all() const { return _all_items; }
const std::vector<T>& added() const { return _added_items; }
const std::vector<T>& removed() const { return _removed_items; }
private:
std::vector<T> _all_items;
std::vector<T> _added_items;
std::vector<T> _removed_items;
};
template <typename T, typename TKey, typename ServiceType>
std::function<rxcpp::observable<Update<T,TKey,ServiceType>>(const rxcpp::observable<RawUpdate<T>>&)> reconstitute() {
return [](const rxcpp::observable<RawUpdate<T>>& input) {
auto state = std::make_shared<std::unordered_map<int, T>>();
return input.map([state](RawUpdate<T>& raw) {
if (raw.is_reset) {
std::vector<T> removed;
removed.reserve(state->size());
for (auto& t : *state) {
removed.push_back(std::move(t.second));
}
state->clear();
std::vector<T> all, added;
return Update<T, TKey, ServiceType>(all, added, removed);
}
else {
std::vector<T> removed;
removed.reserve(raw.removed_keys.size());
for (int key : raw.removed_keys) {
auto iter = state->find(key);
if (iter != state->end()) {
removed.push_back(iter->second);
state->erase(iter);
}
}
for (size_t x = 0; x < raw.added_keys.size(); ++x) {
(*state)[raw.added_keys[x]] = raw.added_items[x];
}
std::vector<T> all;
all.reserve(state->size());
for (const auto& item : *state) {
all.push_back(item.second);
}
return Update<T, TKey, ServiceType>(all, raw.added_items, removed);
}
});
};
}
}}//namespace