Skip to content

Have an application-global state that's accessible from request handlers #2805

Answered by asonix
Pierstoval asked this question in Q&A
Discussion options

You must be logged in to vote

Are you looking for something like this?

#[derive(Debug)]
struct Message;
impl Message {
    fn new() -> Self {
        Self
    }
}

#[actix_web::get("/")]
async fn handler(
    sender: actix_web::web::Data<tokio::sync::mpsc::Sender<Message>>,
) -> actix_web::HttpResponse {
    let _ = sender.send(Message::new()).await;
    actix_web::HttpResponse::Ok().finish()
}

fn start_workers(mut receiver: tokio::sync::mpsc::Receiver<Message>) {
    tokio::spawn(async move {
        while let Some(msg) = receiver.recv().await {
            println!("Got message: {:?}", msg);
        }
    });
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let (tx, rx) = tokio::sync::mpsc::channel(8);

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@Pierstoval
Comment options

@Pierstoval
Comment options

Answer selected by Pierstoval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants