How to listen for mspc messages and run an api server with actix rust?

Viewed 49

I am new to rust, just trying to figure out how to listen for mspc messages and run an API server with actix. Currently, the code stops in tokio::spawn which makes sense, not sure what is the right way to implement it.

My code:

#[actix_web::main]
async fn main() -> std::io::Result<()>  {
    let (tx, mut rx): (Sender<Message>, Receiver<Message>) = channel(30);
    let db_client = utils::connection::init()
        .await
        .expect("Failed to connect to DB");

    let _ = tokio::spawn(async move {
        while let Some(msg) = rx.recv().await {
            match msg.msg_type {
                Done => {
                    // Start again
                    println!("Start the task again")
                }
            }
        }
    })
    .await;


    println!("{}", "Server started! 8080");
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(db_client.postgres.clone()))
            .service(sample_api)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
1 Answers

When you .await the result of spawn(), you wait for the spawned task to complete. But it runs infinitely, and by waiting for it you block the code that should send data to rx - so a deadblock.

Remove the .await from it.

Related