Rust

publisher

Module

Publishing from callbacks.

Contents

use utopia_nats::Publisher;
Rust
pub struct Publisher

Publishes through a crate::Connection from code that cannot hold it: subscription callbacks, service handlers, push consumers. Cheap to clone.

A publish is queued and the connection sends it, with every check crate::Connection::publish makes, as soon as the callback returns (or, from anywhere else, at the connection's next read, flush or publish). Errors surface from the connection call that sends it.

Rust
let replies = connection.publisher();
connection
    .subscribe("math.double", Some(Box::new(move |msg: utopia_nats::Message| {
        let value: i64 = std::str::from_utf8(&msg.data)?.parse()?;
        replies.publish(msg.reply_to.unwrap_or_default(), (value * 2).to_string(), None, None);
        Ok(())
    })), None)
    .await?;
let answer = connection.request("math.double", "21", None, None).await?;
assert_eq!(answer.data, "42");