Hi folks,
I wanna know whether exists a way to inject
or pass a new parameter between two futures combinator.
Right now I have the following code and it works for what I need, but don't know if there is something like filter combinator (and
& and_then
) used in warp crate?
Cargo.toml
[dependencies]
futures = "0.3"
tokio = { version = "1.21", features = ["full"] }
src/main.rs
use futures::{FutureExt, TryFutureExt};
fn inject_param<R: Sized + 'static, T: Sized + 'static>(
t: T,
) -> impl FnOnce(
Result<R, ()>,
) -> std::pin::Pin<std::boxed::Box<dyn futures::Future<Output = Result<(R, T), ()>>>> {
|r: Result<R, ()>| std::boxed::Box::pin(async { Ok((r.unwrap(), t)) })
}
fn inject_flat_param<R: Sized + 'static, T: Sized + 'static>(
t: T,
) -> impl FnOnce(R) -> std::pin::Pin<std::boxed::Box<dyn futures::Future<Output = Result<(R, T), ()>>>>
{
|r: R| std::boxed::Box::pin(async { Ok((r, t)) })
}
#[tokio::main]
async fn main() {
let r = comb01()
.and_then(comb02)
.then(inject_param(format!("<Injected-Param>")))
.and_then(comb03)
.and_then(inject_flat_param(format!("<Injected-Flat-Param>")))
.and_then(comb04)
.await
.unwrap();
println!("Final Result: {r}");
}
async fn comb01() -> Result<String, ()> {
Ok(format!("Combitator01"))
}
async fn comb02(s: String) -> Result<String, ()> {
Ok(format!("{s}-Combinator02"))
}
async fn comb03(pass: (String, String)) -> Result<String, ()> {
let (s, injected) = pass;
Ok(format!("{s}-{injected}-Combinator03"))
}
async fn comb04(pass: (String, String)) -> Result<String, ()> {
let (s, injected) = pass;
Ok(format!("{s}-Combinator04-{injected}"))
}
As I've mentioned before it works, however just wanna know if there something more rustly or a native feature that allow me to achieve that behavior.
Thanks beforehand.