From 0a2ef958c0dca21d19e4ffc38ba5a7c4078e182a Mon Sep 17 00:00:00 2001 From: Weicao-CatilGrass <1992414357@qq.com> Date: Sat, 23 May 2026 23:41:04 +0800 Subject: Rework examples and add entry macro for testing --- examples/example-async-support/src/main.rs | 68 ++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 examples/example-async-support/src/main.rs (limited to 'examples/example-async-support/src/main.rs') diff --git a/examples/example-async-support/src/main.rs b/examples/example-async-support/src/main.rs new file mode 100644 index 0000000..12b1b9c --- /dev/null +++ b/examples/example-async-support/src/main.rs @@ -0,0 +1,68 @@ +//! Example Async Runtime Support +//! +//! > This example shows how to drive an async runtime using the `async` feature +//! +//! ## Note +//! +//! When the `async` feature is enabled, **Mingling** provides a different framework implementation, +//! allowing you to use the `async` keyword directly within `#[chain]`. +//! +//! However, you will lose some capabilities: +//! +//! 1. `&mut` resource injection is not available in async chain functions +//! 2. The program will not be able to use panic unwind functionality +//! +//! Run: +//! ```bash +//! cargo run --manifest-path examples/example-async-support/Cargo.toml --quiet -- download README.md +//! ``` +//! +//! Output: +//! ```plaintext +//! Download begin +//! # (Will pause for 1 second here) +//! "README.md" downloaded. +//! ``` + +use mingling::{hook::ProgramHook, prelude::*}; + +#[tokio::main] +async fn main() { + let mut program = ThisProgram::new(); + + program.with_dispatcher(CMDDownload); + + // Add a hook to display when the download begins + program.with_hook(ProgramHook::empty().on_begin(|| println!("Download begin"))); + + // --------- IMPORTANT --------- + // The return values of `exec_*()` related functions have been replaced with Futures + program.exec_and_exit().await; + // --------- IMPORTANT --------- +} + +dispatcher!("download", CMDDownload => EntryDownload); + +pack!(ResultDownloaded = String); + +// --------- IMPORTANT --------- +#[chain] +// vvvvv_ `async` keyword can be used directly here +pub async fn handle_download(args: EntryDownload) -> Next { + let file_name = args.pick(()).unpack(); + fake_download(file_name).await +} + +#[renderer] +// But renderers cannot use the `async` keyword +pub fn render_downloaded(result: ResultDownloaded) { + r_println!("\"{}\" downloaded.", *result); +} +// --------- IMPORTANT --------- + +gen_program!(); + +async fn fake_download(file_name: String) -> ResultDownloaded { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + ResultDownloaded::new(file_name) +} -- cgit