From a48f6c8a446c7461ae565b409942737ca6f0cd35 Mon Sep 17 00:00:00 2001 From: Hirrolot Date: Wed, 29 Jun 2022 01:49:49 +0600 Subject: [PATCH] Use `Arc` in `examples/shared_state.rs` --- Cargo.toml | 1 - examples/shared_state.rs | 25 ++++++++++++++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 94be4d36..a4ece2c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,7 +95,6 @@ tower-http = { version = "0.2.5", features = ["trace"], optional = true } [dev-dependencies] rand = "0.8.3" pretty_env_logger = "0.4.0" -once_cell = "1.9.0" serde = "1" serde_json = "1" tokio = { version = "1.8", features = ["fs", "rt-multi-thread", "macros"] } diff --git a/examples/shared_state.rs b/examples/shared_state.rs index 33f5d4b6..c09fab93 100644 --- a/examples/shared_state.rs +++ b/examples/shared_state.rs @@ -1,27 +1,34 @@ // This bot answers how many messages it received in total on every message. -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; -use once_cell::sync::Lazy; use teloxide::prelude::*; -static MESSAGES_TOTAL: Lazy = Lazy::new(AtomicU64::default); - #[tokio::main] async fn main() { pretty_env_logger::init(); log::info!("Starting shared state bot..."); let bot = Bot::from_env().auto_send(); + let messages_total = Arc::new(AtomicU64::new(0)); - let handler = Update::filter_message().branch(dptree::endpoint( - |msg: Message, bot: AutoSend| async move { - let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed); + let handler = Update::filter_message().endpoint( + |msg: Message, bot: AutoSend, messages_total: Arc| async move { + let previous = messages_total.fetch_add(1, Ordering::Relaxed); bot.send_message(msg.chat.id, format!("I received {previous} messages in total.")) .await?; respond(()) }, - )); + ); - Dispatcher::builder(bot, handler).build().setup_ctrlc_handler().dispatch().await; + Dispatcher::builder(bot, handler) + // Pass the shared state to the handler as a dependency. + .dependencies(dptree::deps![messages_total]) + .build() + .setup_ctrlc_handler() + .dispatch() + .await; }