Hello,
I am trying to use a tokio mpsc channel multiple times. I am passing the tx and rx endpoints into a function. When calling the function multiple times, I can pass in a clone of the tx endpoint, but the rx endpoint is not clone-able, so the function takes ownership and I cannot re-use the rx endpoint on subsequent function calls. I cannot pass the rx endpoint in as a reference because it gets moved inside a new task, and there is a lifetime problem. How can I re-use the rx receiver in multiple functions.
#[cfg(test)]
mod tests {
use tokio::sync::mpsc::{
channel as MpscChannel, Receiver as MpscReceiver, Sender as MpscSender,
};
use tokio::task;
async fn try_send(tx: MpscSender<Vec<u8>>, mut rx: MpscReceiver<Vec<u8>>) {
//create a receiving task
let jh = task::spawn(async move {
let rxd_vec = rx.recv().await;
println!("Rxd: {:?}", rxd_vec);
});
//send somethingto the receiving task
_ = tx.send(vec![1_u8, 2, 3]).await;
jh.await.unwrap();
}
#[tokio::test]
async fn try_multiple_sends() {
let (tx, rx) = MpscChannel::<Vec<u8>>(10);
try_send(tx.clone(), rx).await; //***Calling the function once is fine
//try_send(tx, rx).await; ***Enabling this line causes a build error
}
}
Running the test produces the following:
running 1 test
Rxd: Some([1, 2, 3])
test tests::try_multiple_sends ... ok