Channel receiver is not peekable

Hi,
in an application I'm currently working on, I'd like to test a channel receiver if it has any messages that could be received.
The try_recv() method sort-of-kind-of does that, but in case the receiver indeed has messages, it will extract the message, which forces me to propagate the result through many levels of code in order to not lose the message.

I tried using .iter().peekable() on the receiver, but it's no use, it always blocks.

Why is there no method on the receiver that would indicate whether the receiver has messages? It seems the logic is alredy there somewhere in the try_recv() method, it just seems not exposed in the API. Or is there a technical reason this is not exposed?

2 Likes

I guess it could be exposed, but receiving the thing that's ready is usually the only thing you want to do when you know it's ready. So that's what try_recv does.

Can you explain a little more why you only want to know "there is something", but not receive it?

(The reason peek() blocks is that peek() is a generic iterator adapter; it does not know anything about channels, so it has to advance the iterator and store a received element internally.)

1 Like

There's a thread that runs a loop with a match receiver.recv() statement that decodes incomming commands and then calls a bunch of functions to perform tasks. Some of them take a long time and entail multiple steps. In those, I'd like to check sometimes if there are new commands and in case there are, I want to interrupt the job and return to the top-level loop where the commands are decoded, so that the match receiver.recv() would be invoked on the next loop iteration.

I could of course use try_recv() and return the result, but that requires modifying return type of multiple functions, propagating the data upwards and it's kind of awkward...

1 Like

I see, that makes sense. Maybe you could use two channels, of which one is a "wakeup" channel that just receives dummy values of ()?

I asked a similar question on stackoverflow: rust - How do I sort mpsc::Receivers between collections depending on the message in it? - Stack Overflow

Having the ability to test the presence of a message would kind of solve my problem. @vojtechkral, did you find a solution?