diff --git a/CHANGELOG.md b/CHANGELOG.md index acbb3aff..20029e75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,7 +34,13 @@ The format is based on [Keep a Changelog], and this project adheres to ## _[Unreleased]_ -_nothing new to show for… yet!_ +_nothing new to show for… yet!_> + +_async callback macro_ + +_2024.03.15_ + +- Add macro `async_callback` and `async_any_callback` for async callbacks [#395](https://github.com/1c3t3a/rust-socketio/issue/395) [#399](https://github.com/1c3t3a/rust-socketio/pull/399) ## [0.4.4] - _Bump dependencies_ diff --git a/socketio/src/asynchronous/mod.rs b/socketio/src/asynchronous/mod.rs index 2976dd9a..e57cdf6a 100644 --- a/socketio/src/asynchronous/mod.rs +++ b/socketio/src/asynchronous/mod.rs @@ -4,5 +4,65 @@ mod socket; #[cfg(feature = "async")] pub use client::builder::ClientBuilder; -pub use client::client::Client; -pub use client::client::ReconnectSettings; +pub use client::client::{Client, ReconnectSettings}; + +// re-export the macro +pub use crate::{async_any_callback, async_callback}; + +#[doc = r#" +A macro to wrap an async callback function to be used in the client. + +This macro is used to wrap a callback function that can handle a specific event. + +```rust +use rust_socketio::async_callback; +use rust_socketio::asynchronous::{Client, ClientBuilder}; +use rust_socketio::{Event, Payload}; + +pub async fn callback(payload: Payload, client: Client) {} + +#[tokio::main] +async fn main() { + let socket = ClientBuilder::new("http://example.com") + .on("message", async_callback!(callback)) + .connect() + .await; +} +``` +"#] +#[macro_export] +macro_rules! async_callback { + ($f:expr) => {{ + use futures_util::FutureExt; + |payload: Payload, client: Client| $f(payload, client).boxed() + }}; +} + +#[doc = r#" +A macro to wrap an async callback function to be used in the client. + +This macro is used to wrap a callback function that can handle any event. + +```rust +use rust_socketio::async_any_callback; +use rust_socketio::asynchronous::{Client, ClientBuilder}; +use rust_socketio::{Event, Payload}; + +pub async fn callback_any(event: Event, payload: Payload, client: Client) {} + +#[tokio::main] +async fn main() { + let socket = ClientBuilder::new("http://example.com") + .on_any(async_any_callback!(callback_any)) + .connect() + .await; +} +``` +"#] +#[macro_export] +macro_rules! async_any_callback { + ($f:expr) => {{ + use futures_util::FutureExt; + |event: Event, payload: Payload, client: Client| $f(event, payload, client).boxed() + }}; +}