[Thiago Cafe] Programming is fun!

Quick tip: Type of tokio spawn return

Created by Thiago Guedes on 2024-06-03 19:03:45

Tags:

When I was implementing the metrics task using tokio, I wanted to save the result JoinHandle in a struct and I saw the type being displayed by the IDE: JoinHandle<?>

What does it mean?

When I looked the definition of the function spawn, that's the code:

pub fn spawn<F>(future: F) -> JoinHandle<F::Output>  
where  
    F: Future + Send + 'static,  
    F::Output: Send + 'static,  
{
// ...

In the Future trait, F::Output refers to the return value of the input function.

Now, the piece of code I have is a long running task. That is the piece of code.

let receiver_task = tokio::spawn(async move {  
    println!("Starting metrics receiver");  
    while let Some(event) = rx.recv().await {  
        if let Err(e) = metrics.add(&event.post_name, &event.origin) {  
            error!("Error writing access metric for {}: {}", &event.post_name, e);  
        } else {  
            debug!("Metric event written for {}", &event.post_name);  
        }  
    }  
});

As this function returns nothing, the type is Unit, hence for this lambda I can declare my struct as:

pub struct MetricHandler {  
    receiver_task: JoinHandle<()>,  
    //...
}

And now you can do:

let receiver_task = tokio::spawn(async move {
// ...
MetricHandler {
	receiver_task,
	// ...
}

Tell me your opinion!

Reach me on Twitter - @thiedri