Providing stream to func taking future in tokio

Future/Tokio Noob here.

Quoting from Tokio's home page example:

extern crate tokio;

use tokio::net::TcpListener;
use tokio::prelude::*;

fn process(s: TcpStream)
  -> impl Future<Item = (), Error = ()> + Send
{ ... }

let addr = "127.0.0.1:8080".parse().unwrap();
let listener = TcpListener::bind(&addr).unwrap();

let server = listener.incoming()
    .map_err(|e| println!("error = {:?}", e))
    .for_each(|socket| {
        tokio::spawn(process(socket))
    });

tokio::run(server);

tokio::run actually takes a future. But in this example, server implements Stream. I realize a Stream can be viewed as Future, but tokio::run explicitly accepts only Future<Item = (), Error = ()>. But the stream is of TcpStream and not (). I realize a stream of () would be pointless, but does this mean that I can give ANY stream to a function that takes Future<Item=(), Error=()> ?

I'm definitely missing something. Could someone please shed some light ?

server is a Future here because it's the ForEach struct (returned from for_each()), and that struct implements Future (which resolves once the stream it's "iterating over" is exhausted, or an error occurs).

1 Like