How to use tonic's `serve_with_shutdown`

Tonic's test's has this snippet:

 let (tx, rx) = oneshot::channel::<()>();
 let jh = tokio::spawn(async move {
        Server::builder()
            .add_service(svc)
            .serve_with_shutdown("127.0.0.1:1322".parse().unwrap(), rx.map(drop))
            .await
            .unwrap();
    });

My questions are:

  1. what is drop here?
  2. can I use broadcast or mpsc here instead of oneshot?
  3. for tokio 1.9.0, oneshot::Receiver<> self implemetes Future, can I use it directly?

As far as I understand serve_with_shutdown will serve requests until the future returns a value (in this case the receiver side of a oneshot channel)

In case of an mpsc channel you will need to .recv() to get a future.

The .map(|_| ()) is necessary to turn a future returning Result<(), RecvError> into one returning ().

1 Like

I tried to use rx.map(|_| ()), but compiler complains that another trait is not satisfied.

    |
57  |             _ = grpc_server.serve_with_shutdown(self.addr, rx.map(|_| ())) => {
    |                                                               ^^^ method cannot be called on `tokio::sync::oneshot::Receiver<()>` due to unsatisfied trait bounds
    |
   ::: /Users/zp/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/tokio-1.9.0/src/sync/oneshot.rs:124:1
    |
124 | pub struct Receiver<T> {
    | ---------------------- doesn't satisfy `tokio::sync::oneshot::Receiver<()>: Iterator`
    |
    = note: the following trait bounds were not satisfied:
            `tokio::sync::oneshot::Receiver<()>: Iterator`
            which is required by `&mut tokio::sync::oneshot::Receiver<()>: Iterator`
    = help: items from traits can only be used if the trait is in scope
    = note: the following trait is implemented but not in scope; perhaps add a `use` for it:
            `use futures_util::future::future::FutureExt;`

Add use futures_util::FutureExt; in the beginning to introduce necessary traits. Solved.

The problem is that it was trying to use the wrong map function.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.