How to advance the swarm state before entering the main eventloop #2041
-
Hi, so this eventloop, closely taken from one of the chat examples, advances the swarm state with the next calls. Currently in order to get the adresses printed, I need to first pass an empty line, so the select! macro is passed through twice. I assume this is necessary because the swarm.next() needs to be polled twice before the Swarm::listeners(&swarm) call returns any adresses. let mut listening = false;
loop {
if !listening {
for addr in Swarm::listeners(&swarm) {
println!("Listening on {:?}", addr);
listening = true;
}
}
let to_publish = {
tokio::select! {
line = stdin.next_line() => {
let line = line.unwrap().expect("stdin closed");
if line != "" {
dbg!(&line);
Some((gossipsub_topic.clone(), line))
} else {
println!("{}", line);
None
}
}
event = swarm.next() => {
// All events are handled by the `NetworkBehaviourEventProcess`es.
// I.e. the `swarm.next()` future drives the `Swarm` without ever
// terminating.
panic!("Unexpected event: {:?}", event);
}
}
};
if let Some((topic, line)) = to_publish {
swarm.publish(topic.clone(), line.as_bytes()).unwrap();
}
println!("hi");
} But this is a clumsy way of doing this. Is there a way to advance the swarm state a bit beforehand? I tried manually polling it, but I'm not sure how to get that to work. Like so (but this doesn't seem to progress the swarm state so that the addresses become available): while Swarm::listeners(&swarm).peekable().peek().is_none() {
match future::poll_fn(|cx| Poll::Ready(Pin::new(&mut swarm).poll_next(cx))).await {
Poll::Ready(_) => panic!(),
Poll::Pending => (),
};
println!("hi");
tokio::time::sleep(Duration::from_millis(100)).await;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
This worked quite well for me: future::poll_fn(|cx| {
if Swarm::listeners(&swarm).peekable().peek().is_some() {
Poll::Ready(None)
} else {
Pin::new(&mut swarm).poll_next(cx)
}
}).await; |
Beta Was this translation helpful? Give feedback.
This worked quite well for me: