I'm reading this example from async-std book:
use async_std::{
io::{stdin, BufReader},
net::{TcpStream, ToSocketAddrs},
prelude::*,
task,
};
use futures::{select, FutureExt};
// Some functions omitted
async fn try_run(addr: impl ToSocketAddrs) -> Result<()> {
let stream = TcpStream::connect(addr).await?;
let (reader, mut writer) = (&stream, &stream);
let mut lines_from_server = BufReader::new(reader).lines().fuse(); // .fuse() called here 1st time
let mut lines_from_stdin = BufReader::new(stdin()).lines().fuse(); // .fuse() called here 1st time
loop {
select! {
line = lines_from_server.next().fuse() => match line { // .fuse() called here 2nd time
Some(line) => {
let line = line?;
println!("{}", line);
},
None => break,
},
line = lines_from_stdin.next().fuse() => match line { // .fuse() called here 2nd time
Some(line) => {
let line = line?;
writer.write_all(line.as_bytes()).await?;
writer.write_all(b"\n").await?;
}
None => break,
}
}
}
Ok(())
}
The parts of the code that are confusing to me are this where streams are fused upon initialization:
let mut lines_from_server = BufReader::new(reader).lines().fuse(); // .fuse() called here 1st time
let mut lines_from_stdin = BufReader::new(stdin()).lines().fuse(); // .fuse() called here 1st time
and later here consuming the stream .fuse()
is called again:
line = lines_from_server.next().fuse() => match line {} // .fuse() called here 2nd time
line = lines_from_stdin.next().fuse() => match line {} // .fuse() called here 2nd time
Why it is needed to call .fuse()
twice like that, when creating the streams and when consuming?
Why .await
is not used?
Why do we need to fuse the streams at all in this case, because when first None
is found loop is exited and program ends?