Forward futures::channel::mpsc::channel

Hi!
I have two channels:

let (tx_a, rx_a) = futures::channel::mpsc::channel::<A>(10);
let (tx_b, rx_b) = futures::channel::mpsc::channel::<B>(10);

Now I want to redirect all mesages from rx_a to tx_b with message conversion A --> B. The only solution I see is to make a tokio task where I forward this manually:

tokio::task::spawn(async move {
    while let Some(a) = rx_a.next().await {
        tx_b.send(B::from(a)).await;
    }
})

Can it be done in a more clean way. Can this be done without tokio tasks?

One option is to use StreamExt::map on the receiver to transform it inside the call to .next(), although then the receiver no long has the type receiver (it is some other kind of Stream).

It's an interesting question. In my understanding, these channels are futures (i.e. async), so you have to run an executor to get the result. And the executor has to run a task or something like it, even it's just a block_on.

Maybe I would try a different async runtime (e.g. smol) and/or channel (async-channel) if you didn't want to use tokio due to some particular reason, or refactor the channel design (e.g. use just one channel instead of two channels).

Just my 2cents.

Yeah the first channel's sender is fed inside some task, receiver of the second channel is awaited in another task. But when I want to forward messages between channels I need another task. Just thought there's already some way to make networks out of channels.

My wild guess is that, there are multiple senders for the 2nd channel? and multiple receivers for the 1st channel? Otherwise, you might consider sending B::from(a) directly to 2nd channel (without using 1st channel) ? Just a thought.

EDIT: you're using mpsc, so the 1st channel can only have one receive.

Originally I did not mention that two channels are forced by architecture. Like you have 1st channel staring from some library and the second is say for collecting events from multiple channels of 1st type.

The advice here about executors is somewhat misguided. Channels don't care about executors. Use the executor you are already using.

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.