Class Topic

Synopsis

#include <lib/inc/drogon/PubSubService.h>

template <typename MessageType>
class Topic : public trantor::NonCopyable

Description

This class template presents an unnamed topic.

Template Parameters:

MessageType -

Inheritance

Ancestors: NonCopyable

Methods

clearRemove all subscribers from the topic.
emptyCheck if the topic is empty.
publishPublish a message, every subscriber in the topic will receive the message.
subscribeSubcribe to the topic.
unsubscribeUnsubscribe from the topic.

Source

Lines 32-117 in lib/inc/drogon/PubSubService.h.

template <typename MessageType>
class Topic : public trantor::NonCopyable
{
  public:
    using MessageHandler = std::function<void(const MessageType &)>;
#if __cplusplus >= 201703L | defined _WIN32
    using SharedMutex = std::shared_mutex;
#else
    using SharedMutex = std::shared_timed_mutex;
#endif
    /**
     * @brief Publish a message, every subscriber in the topic will receive the
     * message.
     *
     * @param message
     */
    void publish(const MessageType &message) const
    {
        std::shared_lock<SharedMutex> lock(mutex_);
        for (auto &pair : handlersMap_)
        {
            pair.second(message);
        }
    }

    /**
     * @brief Subcribe to the topic.
     *
     * @param handler is invoked when a message arrives.
     * @return SubscriberID
     */
    SubscriberID subscribe(const MessageHandler &handler)
    {
        std::unique_lock<SharedMutex> lock(mutex_);
        handlersMap_[++id_] = handler;
        return id_;
    }

    /**
     * @brief Subcribe to the topic.
     *
     * @param handler is invoked when a message arrives.
     * @return SubscriberID
     */
    SubscriberID subscribe(MessageHandler &&handler)
    {
        std::unique_lock<SharedMutex> lock(mutex_);
        handlersMap_[++id_] = std::move(handler);
        return id_;
    }

    /**
     * @brief Unsubscribe from the topic.
     */
    void unsubscribe(SubscriberID id)
    {
        std::unique_lock<SharedMutex> lock(mutex_);
        handlersMap_.erase(id);
    }

    /**
     * @brief Check if the topic is empty.
     *
     * @return true means there are no subscribers.
     * @return false means there are subscribers in the topic.
     */
    bool empty() const
    {
        std::shared_lock<SharedMutex> lock(mutex_);
        return handlersMap_.empty();
    }
    /**
     * @brief Remove all subscribers from the topic.
     *
     */
    void clear()
    {
        std::unique_lock<SharedMutex> lock(mutex_);
        handlersMap_.clear();
    }

  private:
    std::unordered_map<SubscriberID, MessageHandler> handlersMap_;
    mutable SharedMutex mutex_;
    SubscriberID id_;
};





Add Discussion as Guest

Log in to DocsForge