crossbeam icon indicating copy to clipboard operation
crossbeam copied to clipboard

Clean way to exit select loop when all channels are disconnected

Open Timmmm opened this issue 4 years ago • 0 comments

I've just had to write code like this, and it seems... inelegant.

      let mut open_channels = 2;
      lwhile open_channels > 0 {
        select! {
          recv(r1) -> p => {
            if let Ok(p) = p {
              ...
            } else {
              if open_channels > 0 { // Just in case.
                open_channels -= 1;
              }
            }
          }
          recv(r2) -> p => {
            if let Ok(p) = p {
              ...
            } else {
              if open_channels > 0 {
                open_channels -= 1;
              }
            }
          }
        }
      }

I feel like there should be a better way. Maybe in addition to the special default case there could be one like finished? So I could just do

      loop {
        select! {
          recv(r1) -> p => {
            if let Ok(p) = p {
              ...
            }
          }
          recv(r2) -> p => {
            if let Ok(p) = p {
              ...
            }
          }
          finished -> break,
        }
      }

Timmmm avatar Dec 01 '20 13:12 Timmmm