Skip to content

Instantly share code, notes, and snippets.

@singulared
Created May 20, 2019 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singulared/547716f0ceab1d972c81c7bd545307d1 to your computer and use it in GitHub Desktop.
Save singulared/547716f0ceab1d972c81c7bd545307d1 to your computer and use it in GitHub Desktop.
multiple futures in one function
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