Home > Software engineering >  How do I pass a future to serve_with_shutdown
How do I pass a future to serve_with_shutdown

Time:12-07

I am building a server and would like to serve until a oneshot receiver tell me to stop. For that I am using tokios serve_with_shutdown. My understanding is that the service will run until the future signal is ready

pub async fn serve_with_shutdown<F: Future<Output = ()>>(
    self, 
    addr: SocketAddr, 
    signal: F
) -> Result<(), Error>

How do I pass the oneshot receiver as a signal?

Passing it directly like serve_with_shutdown(some_addr, receiver); gives me unused implementer of futures::Future that must be used.

I tried implementing my own future. Same error.

pub struct OneShotFut {
    receiver: Mutex<tokio::sync::oneshot::Receiver<()>>,
}

impl Future for OneShotFut {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut rec = self.receiver.lock().unwrap();
        if rec.try_recv().is_err() {
            return Poll::Pending;
        }
        Poll::Ready(())
    }
}

//... 

serve_with_shutdown(some_addr, OneShotFut {
                receiver: Mutex::new(receiver),
            })

I cannot await the future when passing ti to serve_with_shutdown, since that will directly return ()

CodePudding user response:

Since serve_with_shutdown is an async fn it returns a Future that too must be awaited:

Inside another async fn:

serve_with_shutdown((some_addr, OneShotFut {
    receiver: Mutex::new(receiver),
}).await
  • Related