- Inside the bin folder, create a new file called oneshot.rs.
- Add the following code and run it with cargo run --bin oneshot:
1 extern crate futures;
2
3 use futures::prelude::*;
4 use futures::channel::oneshot::*;
5 use futures::executor::block_on;
6 use futures::future::poll_fn;
7 use futures::stream::futures_ordered;
8
9 const FINISHED: Result<Async<()>, Never> =
Ok(Async::Ready(()));
10
11 fn send_example() {
12 // First, we'll need to initiate some oneshot channels like
so:
13 let (tx_1, rx_1) = channel::();
14 let (tx_2, rx_2) = channel::();
15 let (tx_3, rx_3) = channel::();
16
17 // We can decide if we want to sort our futures by FIFO
(futures_ordered)
18 // or if the order doesn't matter (futures_unordered)
19 // Note: All futured_ordered()'ed futures must be set as a
Box type
20 let mut ordered_stream = futures_ordered(vec![
21 Box::new(rx_1) as Box<Future>,
22 Box::new(rx_2) as Box<Future>,
23 ]);
24
25 ordered_stream.push(Box::new(rx_3) as Box<Future>);
26
27 // unordered example:
28 // let unordered_stream = futures_unordered(vec![rx_1, rx_2,
rx_3]);
29
30 // Call an API, database, etc. and return the values (in our
case we're typecasting to u32)
31 tx_1.send(7).unwrap();
32 tx_2.send(12).unwrap();
33 tx_3.send(3).unwrap();
34
35 let ordered_results: Vec<_> =
block_on(ordered_stream.collect()).unwrap();
36 println!("Ordered stream results: {:?}", ordered_results);
37 }
38
39 fn check_if_closed() {
40 let (tx, rx) = channel::();
41
42 println!("Is our channel canceled? {:?}", tx.is_canceled());
43 drop(rx);
44
45 println!("Is our channel canceled now? {:?}",
tx.is_canceled());
46 }
47
48 fn check_if_ready() {
49 let (mut tx, rx) = channel::();
50 let mut rx = Some(rx);
51
52 block_on(poll_fn(|cx| {
53 println!("Is the transaction pending? {:?}",
54 tx.poll_cancel(cx).unwrap().is_pending());
55 drop(rx.take());
56
57 let is_ready = tx.poll_cancel(cx).unwrap().is_ready();
58 let is_pending =
tx.poll_cancel(cx).unwrap().is_pending();
59
60 println!("Are we ready? {:?} This means that the pending
should be false: {:?}",
61 is_ready,
62 is_pending);
63 FINISHED
64 }))
65 .unwrap();
66 }
67
68 fn main() {
69 println!("send_example():");
70 send_example();
71
72 println!("
check_if_closed():");
73 check_if_closed();
74
75 println!("
check_if_ready():");
76 check_if_ready();
77 }
..................Content has been hidden....................
You can't read the all page of ebook, please click
here login for view all page.