Bridging two mpsc channels

⚓ Rust    📅 2026-06-02    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Bridging two mpsc channels

Today I wrote this function:

/// Bridge two channels.
///
/// This function will read all messages from `input`, convert them to the message type of `output`
/// and send it to the output channel.
///
/// This function will terminate once either the input channel is exhausted or the output channel
/// has been closed.
pub async fn bridge<T, U>(mut input: Receiver<T>, output: Sender<U>)
where
    T: Into<U>,
{
    while let Some(msg) = input.recv().await {
        if let Err(error) = output.send(msg.into()).await {
            error!("Target channel closed: {error}");
            break;
        }
    }
}

Usage:

tokio::spawn(bridge(self.callbacks, message_tx.clone()));

I feel like something like this should/could be a general purpose library function.
I looked for something like this in tokio and searched for other crates, but couldn't find anything like it.
Is there something I overlooked in terms of library functions to bridge two mpsc channels or is there even a better way to do this?

4 posts - 4 participants

Read full topic

🏷️ Rust_feed