The idea of my code is running two concurrent tasks and reading messages from one of them. The other one listens for a stop signal which will make both the concurrent tasks halt. However when I am trying to spawn this task from my main thread, compiler says that the struct that does the tasks does not live long enough.
use std::time::Duration;
use tokio::sync::{
mpsc::{unbounded_channel, UnboundedSender},
oneshot::{channel, Receiver},
};
struct Actor {}
impl Actor {
async fn act(&self, mut stop_listener: Receiver<()>, result_channel: UnboundedSender<u64>) {
let part_1_jh = async {
loop {
if stop_listener.try_recv().is_ok() {
return;
}
println!("Hello from p1");
tokio::time::sleep(Duration::from_millis(400)).await;
}
};
let part_2_jh = async {
loop {
println!("Hello from p2");
result_channel.send(43).unwrap();
tokio::time::sleep(Duration::from_millis(700)).await;
}
};
tokio::join!(part_1_jh, part_2_jh);
}
}
#[tokio::main]
async fn main() {
let (stop_tx, stop_rx) = channel::<()>();
let (result_tx, mut result_rx) = unbounded_channel::<u64>();
let actor = Actor {};
tokio::task::spawn(actor.act(stop_rx, result_tx)); // problematic
let mut total = 0;
loop {
if let Ok(n) = result_rx.try_recv() {
if total < 100 {
total += n;
} else {
stop_tx.send(()).unwrap();
break;
}
}
}
println!("{total}");
}
The error message: Rust Playground
How can I circumvent this?