Channels already handle this, by default. The receiver will not fail when senders go out of scope if there are pending messages. It will keep the messages, and return "disconnected" error only after you receive all pending messages.
fn main() {
let rx = {
let (tx, rx) = std::sync::mpsc::sync_channel(10);
for value in 0..10 {
tx.send(value).unwrap();
}
rx
};
loop {
let value = rx.recv();
println!("{value:?}");
if value.is_err() {
break;
}
}
}