Tokio::spawn problem

extern crate tokio;
extern crate futures;
extern crate tokio_timer;

use futures::{Future, stream, Stream, Sink};
use futures::future::lazy;
use futures::sync::mpsc;
use std::{thread,time};

fn main() {
    let task = lazy(||{
        let (tx,rx) = mpsc::channel(1024);
        let fut = lazy(||{
            stream::iter_ok(0..10).fold(tx,|tx, i| {
                let t = time::Duration::from_millis(1500);
                tx.send(format!("msg from task {}", i)).map_err(|e| {
                    println!("send error: {:?}", e)
        tokio::spawn( fut );  // can not compile

        rx.for_each(|msg| {
            println!("Got {}", msg);
            println!("error: {:?}", e);


lazy crate a future,
tokio::spawn takes a future as parameter right? so why can not compile?

tokio::spawn takes a Future<Output = ()>, or in other words, a future that resolves to nothing. This is to force you to handle the output of the future, rather than having the runtime silently swallow it.

The simplest fix would be to do tokio::spawn(|_| {})), which throws away the output of fut.

1 Like

Note that you should not use blocking functions such as thread::sleep inside a future. Instead use tokio_timer to wait in a way that allows the executor to work on other things while your future is sleeping.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.