12

Currently my main function, where the server starts looks like this

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let address = "0.0.0.0:3000";

    HttpServer::new(move || {
        let app_state = {...some state};
        App::new()
            .data(app_state)
            .wrap(middleware::Logger::default())
            .service(network_api::init_service())
    })    
    .bind(address)?
    .run()
    .await
}

Once the server starts, I want to run one (async) function, to make a request to another server, and that server should respond with another request to this server that just got up and running.

Not sure I see in the documentation anything mentioning a callback function that is run only once on server start.

For example maybe having it in run() function, like this:

run(|| {
  // server started now perform some request or whatever
  Client::new().post(&url).json(json_stuff).send().await
})

Edit I think I solved it, will post answer when I can answer my own question

high incompetance
  • 2,500
  • 4
  • 18
  • 26

2 Answers2

4

I have solved this by joining 2 async functions, created another async function

async fn another_func() -> Result<()> {
...
}

and have used future::join() like this

let server = HttpServer::new(move || {
        let app_state = {...some state};
        App::new()
            .data(app_state)
            .wrap(middleware::Logger::default())
            .service(network_api::init_service())
    })    
    .bind(address)?
    .run();

future::join(server, another_func()).await;

Ok(()

Of course if anyone has a better answer please post it

high incompetance
  • 2,500
  • 4
  • 18
  • 26
  • This should be `futures::join(server, another_func());` without the `.await` and the `future` should have an `s`. Add `futures` to your cargo dependencies section. – NyproTheGeek Oct 17 '21 at 13:09
0

I actually struggled with it a bit and eventually replaced the future::join with tokio join! macro as follows:

tokio::join!(server, utils::open_web_app(server_address));

Ok(())
liron_hazan
  • 1,396
  • 2
  • 19
  • 27