Skip to content

Commit

Permalink
Ch. 17 §03: restore accidentally-removed Listing 17-14
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskrycho committed Jul 15, 2024
1 parent 92c19ce commit c3c88e4
Show file tree
Hide file tree
Showing 4 changed files with 350 additions and 2 deletions.
292 changes: 292 additions & 0 deletions listings/ch17-async-await/listing-17-14/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions listings/ch17-async-await/listing-17-14/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
trpl = { path = "../../../packages/trpl" }
48 changes: 48 additions & 0 deletions listings/ch17-async-await/listing-17-14/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use std::time::Duration;

fn main() {
trpl::block_on(async {
let (tx, mut rx) = trpl::channel();

let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];

for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};

let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};

let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];

for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};

// ANCHOR: here
let futures = vec![tx1_fut, rx_fut, tx_fut];

trpl::join_all(futures).await;
// ANCHOR_END: here
});
}
3 changes: 1 addition & 2 deletions src/ch17-03-more-futures.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ To check all the futures in some collection, we will need to iterate over and
join on *all* of them. The `trpl::join_all` function accepts any type which
implements the `Iterator` trait, which we learned about back in Chapter 13, so
it seems like just the ticket. Let’s try putting our futures in a vector, and
replace `join3` with `join_all`.
replace `join!` with `join_all`.

<Listing number="17-14" caption="Storing anonymous futures in a vector and calling `join_all`">

Expand All @@ -39,7 +39,6 @@ Unfortunately, this does not compile. Instead, we get this error:

<!-- manual-regeneration
cd listings/ch17-async-await/listing-17-14/
cargo clean
cargo build
copy just the compiler error, and *add* the following text (correctly aligned),
to match the nicer version we will have starting in 1.81
Expand Down

0 comments on commit c3c88e4

Please sign in to comment.