Created
May 20, 2019 17:43
-
-
Save singulared/547716f0ceab1d972c81c7bd545307d1 to your computer and use it in GitHub Desktop.
multiple futures in one function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use futures::future::*; | |
fn either(x: Option<i32>) -> impl Future<Item = i32, Error = i32> { | |
match x { | |
Some(x) => Either::A(ok(x).map(|x| x)), | |
None => Either::B(ok(42).and_then(|x| err(x))) | |
} | |
} | |
fn boxed(x: Option<i32>) -> Box<Future<Item = i32, Error = i32>> { | |
match x { | |
Some(x) => Box::new(ok(x).map(|x| x)), | |
None => Box::new(ok(42).and_then(|x| err(x))) | |
} | |
} | |
fn chained(x: Option<i32>) -> impl Future<Item = i32, Error = i32> { | |
let fut = match x { | |
Some(x) => ok(x), | |
None => err(42), | |
}; | |
let fut = fut.map_err(|error| error); | |
let fut = fut.and_then(|x| ok(x + 1)); | |
fut.map(|x| x) | |
} | |
fn main() { | |
let mut future = either(None); | |
println!("Either: {:#?}", future.poll()); | |
let mut future = either(Some(32)); | |
println!("Either: {:#?}", future.poll()); | |
let mut future = boxed(None); | |
println!("Either: {:#?}", future.poll()); | |
let mut future = boxed(Some(32)); | |
println!("Either: {:#?}", future.poll()); | |
let mut future = chained(None); | |
println!("Chained: {:#?}", future.poll()); | |
let mut future = chained(Some(32)); | |
println!("Chained: {:#?}", future.poll()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment