3

I need to save a ready or pending future in a variable depending on a condition.

Would be nice if I could do this:

let f = futures::future::ready(true);

But the API provides two different functions, which have different return types, so, this does not work either:

let f = if true { futures::future::ready(()) } else { futures::future::pending::<()>() }

I understand that I can implement my own future for this, but I wonder if there is a way to make the if expression work?

nicolai
  • 1,140
  • 9
  • 17

1 Answers1

4

You can use the futures::future::Either type:

use futures::future::Either;
use std::future::{pending, ready, Future};

pub fn pending_or_ready(cond: bool) -> impl Future<Output = ()> {
    if cond {
        Either::Left(ready(()))
    } else {
        Either::Right(pending())
    }
}

(Playground)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841