0

Rust newbie here since I recently started working on it. I'm trying get a rest api working and the following code works completely fine for me.

MyRest.rs

pub struct RestBro;

impl RestBro {

    pub async fn run_bro() {
        let routes_post = warp::post()
            .and(warp::path!("v1" / "homie").and_then(my_function));

        warp::serve(routes)
            .run(([127, 0, 0, 1], 3003))
            .await;    
    }

}

main.rs

#[tokio::main]
async fn main() {
    let rb = RestBro;
    rb.run_bro().await;
}

Now the thing is that I don't want my main to be an async and I just can't figure out how to run that run_bro() function indefinitely like its happening above. I've tried block_on and that just blocks and waits for run_bro to interrupt which is expected and when I tried spawn it just runs through and exits. The documentation on Tokio confused me and that's why I'm looking for some help here.

block_on

fn main() {
    let async_block = async {
        let rb = RestBro;
        rb.run_bro().await;
    };
    let tr = tokio::runtime::Runtime::new().unwrap();
    tr.block_on(async_block);
    println!("Everything working good!");
}

spawn

fn main() {
    let tr = tokio::runtime::Runtime::new().unwrap();
    tr.spawn(async {
        let rb = RestBro;
        rb.run_bro().await;
    });
    println!("Everything working good!");
}

To be clear, my question is how can I call asynchronous run_bro() function and await from a synchronous main? Thanks in advance!!

M. Ather Khan
  • 305
  • 1
  • 2
  • 9

1 Answers1

1

To be clear, my question is how can I call asynchronous run_bro() function and await from a synchronous main?

I do not understand why you'd want to wrap server in spawn. In your code, it's not working because your main program closes and the spawn closes with it.

fn main() {
    let tr = tokio::runtime::Runtime::new().unwrap();
    tr.spawn(async {
        let rb = RestBro;
        rb.run_bro().await;
    });
    println!("Everything working good!");
}

If you change it to this it'll work for five seconds.

use std::{thread, time};

fn main() {
    let tr = tokio::runtime::Runtime::new().unwrap();
    tr.spawn(async {
        let rb = RestBro;
        rb.run_bro().await;
    });
    println!("Everything working good!");
    thread::sleep(time::Duration::from_secs(5));
}

Or indefinitely:

fn main() {
    let tr = tokio::runtime::Runtime::new().unwrap();
    tr.spawn(async {
        let rb = RestBro;
        rb.run_bro().await;
    });
    println!("Everything working good!");
    tr.join().unwrap();
}
t56k
  • 6,769
  • 9
  • 52
  • 115
Zeppi
  • 1,175
  • 6
  • 11