I am trying to implement a Promise system with Tokio, I simulate the callback and the resolve, this is the code:
use std::time::Duration;
use tokio::sync::oneshot::{channel};
use tokio::time::sleep;
async fn task_prom(callback: impl Fn(i32)) {
for x in 1..=10 {
if x == 10 {
callback(x);
}
sleep(Duration::from_secs(1)).await;
}
}
async fn handler() -> i32 {
let (tx, rx) = channel::<i32>();
task_prom(move |x| tx.send(x).unwrap()).await;
rx.await.unwrap()
}
#[tokio::main]
async fn main() {
let res = handler().await;
println!("{}", res);
}
When I try to run, I get this error:
error[E0507]: cannot move out of `tx`, a captured variable in an `Fn` closure
--> src\main.rs:17:24
|
16 | let (tx, rx) = channel::<i32>();
| -- captured outer variable
17 | task_prom(move |x| tx.send(x).unwrap()).await;
| -------- ^^ ------- `tx` moved due to this method call
| | |
| | move occurs because `tx` has type `tokio::sync::oneshot::Sender<i32>`, which does not implement the `Copy` trait
| captured by this `Fn` closure
|
note: `tokio::sync::oneshot::Sender::<T>::send` takes ownership of the receiver `self`, which moves `tx`
--> C:\Users\titof\.cargo\registry\src\index.crates.io-6f17d22bba15001f\tokio-1.28.1\src\sync\oneshot.rs:594:21
|
594 | pub fn send(mut self, t: T) -> Result<(), T> {
|
^^^^
I see the Tokio's documentation, but I don't know why I have this error. Thanks.