diff options
| author | Weicao-CatilGrass <1992414357@qq.com> | 2026-05-23 23:41:04 +0800 |
|---|---|---|
| committer | Weicao-CatilGrass <1992414357@qq.com> | 2026-05-23 23:49:34 +0800 |
| commit | 0a2ef958c0dca21d19e4ffc38ba5a7c4078e182a (patch) | |
| tree | c82fc4242ed393b132ba514eb434d722e7d9c387 /examples/example-async-support/src | |
| parent | ccab1940c019dfbfb7dfcbbe4cb927258933755f (diff) | |
Rework examples and add entry macro for testing
Diffstat (limited to 'examples/example-async-support/src')
| -rw-r--r-- | examples/example-async-support/src/main.rs | 68 |
1 files changed, 68 insertions, 0 deletions
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) +} |
