eclipse / paho.mqtt.rust

paho.mqtt.rust
Other
524 stars 102 forks source link

How to async publish and subscribe data to/from client. #211

Open filober opened 11 months ago

filober commented 11 months ago

Hi, I'm currently working on a Rust project where I'm using Tokio to create concurrent tasks for publishing and subscribing to an MQTT broker. In my setup, I have two tasks that share the same client. One task publishes data every 5 seconds, while the other continuously listens for incoming subscribed messages.

I'm using the following code to read the subscribed data:

let result = strm.next().await;

if let Some(Some(msg)) = result {
    println!("{}", msg);
}

The issue I'm facing is that the strm.next().await call doesn't block the execution of another task but locks the shared data needed to execute the other task. How can I modify my code to handle message reception asynchronously and avoid locking shared data, ensuring concurrent execution of tasks?

Additionally, I'm looking for an example of how to asynchronously publish and subscribe to MQTT data in Rust. Do you have any examples or recommendations for this? Thanks!

fpagliughi commented 11 months ago

I don't have anything in the repo that spawns separate tasks for publishing and subscribing. I've been trying to keep the library agnostic to an async executor. But going forward, it seems like I should make optional features for different executors (tokio, async-std, smol) and compile in examples specific to each. That would also allow for more complete examples like spawning, etc.

Not that the library itself would do anything different for each, but that having specific examples for tokio and all would help new people get started.

But I'm not aware of any locking problem. The asynchronous streaming (consuming) API simply gets a callback internally in the library and places the messages in an async channel which you can read from an async context (task) art your leisure.

Can you post a small example (as small as possible) of what is not working?