use select! oneshot "called after complete" error #3812
Answered
by
Darksonn
daiguadaidai
asked this question in
Q&A
-
I want to use ** my code
** Error
|
Beta Was this translation helpful? Give feedback.
Answered by
Darksonn
May 25, 2021
Replies: 1 comment 1 reply
-
The easiest is to use a channel that has support for using it after it has been closed such as an use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx1, mut rx1) = mpsc::channel(1);
let (tx2, mut rx2) = mpsc::channel(1);
tokio::spawn(async move {
let _ = tx1.send("one").await;
});
tokio::spawn(async move {
let _ = tx2.send("two").await;
});
for _ in 0..2 {
tokio::select! {
Some(val) = rx1.recv() => {
println!("rx1 comopleted first with {:?}", val);
}
Some(val) = rx2.recv() => {
println!("rx2 comopleted first with {:?}", val);
}
}
}
} To do this with an oneshot channel, there are some options, but the easiest is to fuse it. use tokio::sync::oneshot;
use futures::future::FutureExt;
#[tokio::main]
async fn main() {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
tokio::spawn(async move {
let _ = tx1.send("one");
});
tokio::spawn(async move {
let _ = tx2.send("two");
});
let mut rx1 = rx1.fuse();
let mut rx2 = rx2.fuse();
for _ in 0..2 {
tokio::select! {
val = &mut rx1 => {
println!("rx1 comopleted first with {:?}", val);
}
val = &mut rx2 => {
println!("rx2 comopleted first with {:?}", val);
}
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Darksonn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The easiest is to use a channel that has support for using it after it has been closed such as an
tokio::sync::mpsc
. Incidentally, this is also the channel that is closest to a Go channel.