From 86b51095555b68b3cb8e67c70238dd5d9abaa468 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 8 Mar 2024 17:20:12 +0800 Subject: [PATCH] docs: Add more examples Signed-off-by: Xuanwo --- src/lib.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 8bc147a..0e93d4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,6 +68,92 @@ //! Ok(()) //! } //! ``` +//! +//! Retry functions with args. +//! +//! ```no_run +//! use anyhow::Result; +//! use backon::ExponentialBuilder; +//! use backon::Retryable; +//! +//! async fn fetch(url: &str) -> Result { +//! Ok(reqwest::get(url).await?.text().await?) +//! } +//! +//! #[tokio::main(flavor = "current_thread")] +//! async fn main() -> Result<()> { +//! let content = (|| async { fetch("https://www.rust-lang.org").await }) +//! .retry(&ExponentialBuilder::default()) +//! .when(|e| e.to_string() == "retryable") +//! .await?; +//! +//! println!("fetch succeeded: {}", content); +//! Ok(()) +//! } +//! ``` +//! +//! Retry functions with receiver `&self`. +//! +//! ```no_run +//! use anyhow::Result; +//! use backon::ExponentialBuilder; +//! use backon::Retryable; +//! +//! struct Test; +//! +//! impl Test { +//! async fn fetch(&self, url: &str) -> Result { +//! Ok(reqwest::get(url).await?.text().await?) +//! } +//! } +//! +//! #[tokio::main(flavor = "current_thread")] +//! async fn main() -> Result<()> { +//! let test = Test; +//! let content = (|| async { test.fetch("https://www.rust-lang.org").await }) +//! .retry(&ExponentialBuilder::default()) +//! .when(|e| e.to_string() == "retryable") +//! .await?; +//! +//! println!("fetch succeeded: {}", content); +//! Ok(()) +//! } +//! ``` +//! +//! Retry functions with receiver `&mut self`. +//! +//! ```no_run +//! use anyhow::Result; +//! use backon::ExponentialBuilder; +//! use backon::RetryableWithContext; +//! +//! struct Test; +//! +//! impl Test { +//! async fn fetch(&mut self, url: &str) -> Result { +//! Ok(reqwest::get(url).await?.text().await?) +//! } +//! } +//! +//! #[tokio::main(flavor = "current_thread")] +//! async fn main() -> Result<()> { +//! let test = Test; +//! +//! let (_, result) = (|mut v: Test| async { +//! let res = v.fetch("https://www.rust-lang.org").await; +//! // Return input context back. +//! (v, res) +//! }) +//! .retry(&ExponentialBuilder::default()) +//! // Passing context in. +//! .context(test) +//! .when(|e| e.to_string() == "retryable") +//! .await; +//! +//! println!("fetch succeeded: {}", result.unwrap()); +//! Ok(()) +//! } +//! ``` #![deny(missing_docs)] #![deny(unused_qualifications)]