From b78423377c3f2fbcfcb31d974c63691c4e1a3630 Mon Sep 17 00:00:00 2001 From: kjuulh Date: Wed, 7 Aug 2024 17:09:45 +0200 Subject: [PATCH] docs: add examples this is to show how we can use closures in the mad component context. It isn't super pretty because of the async closure, so we need to show the slighly complicated syntax Signed-off-by: kjuulh --- README.md | 8 ++++++++ crates/mad/examples/fn/main.rs | 24 ++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 28cfa08..1690b58 100644 --- a/README.md +++ b/README.md @@ -41,3 +41,11 @@ async fn main() -> anyhow::Result<()> { } ``` +## Examples + +Can be found (here)[crates/mad/examples] + +- basic +- fn +- signals +- error_log diff --git a/crates/mad/examples/fn/main.rs b/crates/mad/examples/fn/main.rs index 02bba2e..b746597 100644 --- a/crates/mad/examples/fn/main.rs +++ b/crates/mad/examples/fn/main.rs @@ -10,7 +10,7 @@ impl mad::Component for WaitServer { Some("WaitServer".into()) } - async fn run(&self, cancellation: CancellationToken) -> Result<(), mad::MadError> { + async fn run(&self, _cancellation: CancellationToken) -> Result<(), mad::MadError> { let millis_wait = rand::thread_rng().gen_range(500..3000); tracing::debug!("waiting: {}ms", millis_wait); @@ -28,9 +28,11 @@ async fn main() -> anyhow::Result<()> { .with_max_level(Level::TRACE) .init(); + let item = "some item".to_string(); + mad::Mad::builder() .add(WaitServer {}) - .add_fn(|cancel| async move { + .add_fn(|_cancel| async move { let millis_wait = 50; tracing::debug!("waiting: {}ms", millis_wait); @@ -40,6 +42,24 @@ async fn main() -> anyhow::Result<()> { Ok(()) }) + .add_fn(move |_cancel| { + // I am an actual closure + + let item = item.clone(); + + async move { + let _item = item; + + let millis_wait = 50; + + tracing::debug!("waiting: {}ms", millis_wait); + + // Simulates a server running for some time. Is normally supposed to be futures blocking indefinitely + tokio::time::sleep(std::time::Duration::from_millis(millis_wait)).await; + + Ok(()) + } + }) .run() .await?;