Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <utility>
- namespace tme
- {
- template<typename Observer, typename Observable>
- class DoUnsubscribe final
- {
- public:
- void operator()(Observable& observable, const Observer&) const
- {
- observable.unsubscribe();
- }
- };
- template <typename Observer, typename Observable, typename Unsubscribe = DoUnsubscribe<Observer, Observable>>
- class AutoUnsubscribe final
- {
- public:
- AutoUnsubscribe() = default;
- explicit AutoUnsubscribe(const Observer& observer)
- : observer_(observer)
- {
- }
- explicit AutoUnsibescribe(Observer&& observer)
- : observer_(std::move(observer))
- {
- }
- AutoUnsubscribe& plug(const Observer& observer)
- {
- unsubscribe();
- observer_ = observer;
- return *this;
- }
- AutoUnsubscribe& plug(Observer&& observer)
- {
- unsubscribe();
- observer_ = std::move(observer);
- return *this;
- }
- Observer subscribe(Observable& host)
- {
- UNI_ASSERT(nullptr == observable_);
- observable_ = &host;
- return observer_;
- }
- ~AutoUnsubscribe()
- {
- unsubscribe();
- }
- private:
- void unsubscribe()
- {
- if (nullptr != observable_)
- {
- Unsubscribe{}(*observable_, observer_);
- }
- }
- Observer observer_;
- Observable* observable_ = nullptr;
- };
- } // namespace tme
- /*
- usage
- */
- class SinkMessagesBuffer final : public UniLog::ILogMessageSink
- {
- public:
- using AutoUnsubscribe = tme::AutoUnsubscribe<std::function<void()>, SinkMessagesBuffer>;
- void subscribe_on_messages_deliver(AutoUnsubscribe& listener)
- {
- on_new_message_ = listener.subscribe(*this);
- }
- void unsubscribe()
- {
- on_new_message_ = {};
- }
- // some other stuff
- private:
- std::function<void()> on_new_message_;
- // some other stuff
- };
- SinkMessagesBuffer log_buffer;
- SinkMessagesBuffer::AutoUnsubscribe log_buffer_connection;
- log_buffer->subscribe_on_messages_deliver(log_buffer_connection.plug([this]() { cool_stuff_on_event(); }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement