Howdy! 
I'm trying to grok async rust, and I have come across yet another question: Why can't I keep a stream as member of a struct?
Consider my first try:
use color_eyre::Result;
use futures::stream::StreamExt;
use tokio;
pub struct Book {}
impl Book {
pub async fn fetch(id: usize) -> usize {
id
}
}
pub struct BookList {
queue: Vec<usize>,
}
impl BookList {
pub fn new(queue: Vec<usize>) -> Self {
Self { queue }
}
pub fn fetch(&self) -> impl futures::Stream<Item = usize> {
let mut work = vec![];
for id in &self.queue {
work.push(Book::fetch(*id));
}
futures::stream::iter(work).buffered(5)
}
}
#[tokio::main]
async fn main() -> Result<()> {
let booklist = BookList::new(vec![1, 2, 3, 4, 5, 6, 7]);
let a = booklist.fetch().next().await;
dbg!(a);
let b = booklist.fetch().next().await;
dbg!(b);
Ok(())
}
This will output
[examples\async.rs:13:5] a = Some(
1,
)
[examples\async.rs:15:5] b = Some(
1,
)
because my stream gets created from scratch every time I call fetch. That's fair enough.
Moving on, I tried this:
pub struct Book {}
impl Book {
pub async fn fetch(id: usize) -> usize {
id
}
}
pub struct BookList {
pub queue: Box<dyn futures::Stream<Item = usize>>
}
impl BookList {
pub fn new(items: Vec<usize>) -> Self {
let mut work = vec![];
for id in items {
work.push(Book::fetch(id));
}
let queue = Box::new(futures::stream::iter(work).buffered(5));
Self { queue }
}
}
use color_eyre::Result;
use futures::stream::StreamExt;
use tokio;
#[tokio::main]
async fn main() -> Result<()> {
let booklist = BookList::new(vec![1, 2, 3, 4, 5, 6, 7]);
let a = booklist.queue.next();
dbg!(a);
let b = booklist.queue.next();
dbg!(b);
Ok(())
}