PrivMX DOCS
C++

Handling Events

Events allow your application to respond to changes in user context instantly. These events are automatically captured when relevant changes occur. You can subscribe to them by registering event listeners.

The EventQueue And Handling Events

Sample code on this page is based on the same initial assumptions.

Key Considerations

Please note the following:

  • Events will only trigger for active connections.
  • Events are not captured unless explicitly listened for.
  • A single instance of the eventQueue is shared across all connections.

Handling The Incoming Event

Below there is simple code example of how to handle an event coming after new message has been sent to the Thread.

#include <privmx/endpoint/core/Connection.hpp>
#include <privmx/endpoint/thread/ThreadApi.hpp>
#include <privmx/endpoint/core/Buffer.hpp>
#include <privmx/endpoint/core/EventQueue.hpp>
#include <privmx/endpoint/thread/Events.hpp>
 
// ...
core::EventQueue eventQueue {core::EventQueue::getInstance()};
 
// Start the EventQueue reading loop
std::thread t([&](){
    while(true) {
        core::EventHolder event = eventQueue.waitEvent();
        if (thread::Events::isThreadNewMessageEvent(event)) {
            auto msgEvent = thread::Events::extractThreadNewMessageEvent(event);
            auto message = msgEvent.data;
            std::cout << "Message: " << message.data.stdString() << std::endl;
            std::cout << "Author: " << message.info.author << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
});
 
// ...
 
// initialize the connection to the Bridge and the Threads API
auto connection {core::Connection::connect(USER1_PRIVATE_KEY, SOLUTION_ID, BRIDGE_URL)};
auto threadApi {thread::ThreadApi::create(connection)};
core::PagingQuery defaultListQuery = {.skip = 0, .limit = 100, .sortOrder = "desc"};
 
// Get a Thread to work with
auto currentThread {threadApi.listThreads(CONTEXT_ID, defaultListQuery).readItems[0]};
 
// Subscribe for the Thread's events
threadApi.subscribeForMessageEvents(currentThread.threadId);
 
// Send a sample message
threadApi.sendMessage(currentThread.threadId, core::Buffer::from(""), core::Buffer::from(""), core::Buffer::from("some message"));
 
t.join();

As soon as the new message arrives to the Thread - the ThreadNewMessageEvent will be emitted and handled by the EventQueue.

We use cookies on our website. We use them to ensure the proper functioning of the site and, if you agree, for purposes we set, such as analytics or marketing.

On this page