Way to connect MPSC channels with different message types?

Is there an API or crate available that allows one to easily adapt one MPSC channel to another MPSC channel with a closure? What I mean is if there is an channel that transmits Foo messages and a channel that transmits Bar messages, I'd like to supply a function that converts Foo to Bar as a closure and connect the Rx of the Foo channel to the Tx of the Bar channel with the closure providing the conversion between the two.

1 Like

Not that I know of, but it's very simple to do yourself. Spawn a thread (or task if async) and forward messages in a loop.

1 Like

Yeah, that's what I thought, but I just wanted to check if there was something already as it seems like such an obvious API to exist. Oh well.

Well it involves spawning a thread which is somewhat expensive so you might not want to hide it behind an innocent function call.

I managed to find this: https://crates.io/crates/transformable_channels.

Does anyone have any experience with it? It seems like it might be the right thing for the problem.

Well, nope, this doesn't help as you can't use the TX/RX from this where the TX/RX from std::mpsc::channel is needed. Bummer.

There are several behaviors that a channel system — including one that's a thin wrapper over std::sync::mpsc — could offer for converting messages, which differ in which thread the conversion happens on (sender, receiver, or a third), timing/laziness, and the consequences of a panic.

So, it's not trivial to just add a conversion — there are behavior choices to make. But if you know which one you want, writing a wrapper that does it isn't hard.

(Of course, your options are constrained if you're dealing with libraries that require std channels only, but if you have such, think of that as an abstraction boundary: you don't get to modify what runs on their thread stack.)

Hmmm....this is an important point I hadn't considered. Good point.

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.