eclipse / paho.mqtt.rust

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

Using with Tokio runtime #162

Closed k-wasniowski closed 1 year ago

k-wasniowski commented 2 years ago

Hey, I am new to Rust, is it possible to combine async_client with Tokio runtime? If it's possible could you provide an example?

fpagliughi commented 2 years ago

Yes. The library came out before async/await, but it has been made compatible with it. Look through the examples directory: https://github.com/eclipse/paho.mqtt.rust/tree/master/examples

All the apps that have the word async_... in the title are pretty close to what you want, as well as any others containing the await keyword. You just need to add the startup code for a specific (Tokio) runtime.

You would use the AsyncClient, like:

let cli = mqtt::AsyncClient::new(uri)?;
...

Then, with that, any function that returns a Token can be await'ed. The tokens implement Future, and wrap a specific ServerResponse. So, if you see a function like this:

pub fn connect<T>(&self, opts: T) -> ConnectToken { ... }

you can think of it as if it were written:

pub async fn connect<T>(&self, opts: T) -> ConnectResponse { ... }

I hope that makes sense.