Async code can be stored as an object — a Future
, but it doesn't do anything while it's sitting in a struct. It needs to be spawned to run.
You can tie it to an object using channels:
let (sender, receiver) = tokio::sync::mpsc::channel(1);
// add your own error handling
spawn(async move {
loop {
let bytes_read = socket.read(&mut buf).await?;
// it'll fail when receiver is dropped
sender.send(buf[0..bytes_read].to_vec())?;
}
});
// store receiver in a struct, and later you can do:
somestruct.receiver.recv().await;
but that's a bit overcomplicated, because usually you'd store socket
in a struct, and just read from it in async fn
.
Callback-based design is rather different than async/future-based design, so I suspect you'll need to adjust your design to fit async code, instead of trying to make async functions work like callbacks.