I have a function load_games_page which loads a single page of a website. And this returns each "game" on that page in a boxed stream of futures.
I have another function load_games which I want to load all games (up to 5 pages) as a single boxed stream of futures.
Though I'm stuck at how I could do this exactly. I've posted my current code, but not sure what's the right approach for this. Any ideas?
/// Returns a stream of futures of `Game`s.
/// If no games are available on this page, `Ok(None)` is returned.
async fn load_games_page(
&self,
sport: Sport,
page: u16,
) -> Result<Option<BoxStream<'_, BoxFuture<Result<Game>>>>> {
// ...
}
async fn load_games(&self, sport: Sport) -> Result<BoxStream<'_, BoxFuture<Result<Game>>>> {
let workers: FuturesOrdered<_> = (0..=5) // load 5 pages
.into_iter()
.map(|page| self.load_games_page(sport, page))
.collect();
let pages: Vec<_> = workers
.try_take_while(|res| future::ready(Ok(res.is_some()))) // if ones page is empty, stop the iterator early
.try_collect()
.await?;
Ok(pages...) // chain streams into one continuous stream
}