I'm trying to implement Future, but it fails:
use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
};
use tokio::time::sleep;
async fn send(url: &str) {
println!("Sending to URL {}", url);
// Simulate the sending process
sleep(Duration::from_millis(500)).await;
}
type Request = Pin<Box<dyn Future<Output = ()>>>;
struct Proxy {
this: Option<Pin<Box<dyn Future<Output = ()>>>>,
requests: Arc<Mutex<Vec<Request>>>,
}
impl Proxy {
fn new() -> Self {
Self {
this: None,
requests: Arc::new(Mutex::new(vec![])),
}
}
fn push(&self, request: Request) {
let requests = self.requests.try_lock().expect("Cannot lock");
requests.push(request);
}
async fn execute_requests(&self) {
let mut requests = self.requests.try_lock().expect("Cannot lock");
while let Some(request) = requests.pop() {
request.await;
}
}
}
impl Future for Proxy {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.this
.get_or_insert_with(|| Box::pin(self.execute_requests()))
.as_mut()
.poll(cx)
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let request_1 = async {
send("url 1").await;
};
let request_2 = async {
send("url 2").await;
};
let mut proxy = Proxy::new();
proxy.push(Box::pin(request_2));
proxy.push(Box::pin(request_1));
Ok(proxy.await)
}
The error:
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> snippet.rs:49:50
|
47 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
| -------------- this data with an anonymous lifetime `'_`...
48 | self.this
49 | .get_or_insert_with(|| Box::pin(self.execute_requests()))
| ^^^^^^^^^^^^^^^^ ...is captured here, requiring it to live as long as `'static`