pub fn from_stream<S: Stream + Unpin>(stream: S) -> FromStream<S> ⓘAvailable on crate feature
futures only.Expand description
“Lifts” and converts an Unpin Stream into an
impl LendingIterator which lends futures (an S,
say).
-
use { ::futures::{ prelude::*, }, ::lending_iterator::{ prelude::*, }, }; let stream = stream::iter(1..=3); let mut lending_iterator = lending_iterator::from_stream(stream); loop { if let Some(item) = lending_iterator.next().unwrap().await { println!("Got `{}`", item); } else { break; } }
This could be useful to get access to the more lifetime-powerful adapters of
this crate (compared to the adapters on StreamExt, for instance).
-
That being said, said adapters often requires the explicitly-turbofished
HKTparameter, which in turn requires nameable types.Sadly, most
impl Futureare unnameable!. So you’ll mostly need to useBoxFutures and whatnot.For
nightlyusers, however,type_alias_impl_traitcan be leveraged to avoid unnecessaryBoxing. Keep it in mind!
For instance, here is what a &mut-based “unfold” async iterator
construction would look like:
-
use { ::futures::{ future::BoxFuture, prelude::*, }, ::lending_iterator::{ prelude::*, }, }; let mut iter = lending_iterator::repeat_mut(0) .map::<HKT!(BoxFuture<'_, Option<i32>>), _>( |[], state: &mut _| async move { if *state <= 2 { let yielded = *state * 2; *state += 1; Some(yielded) } else { None } } .boxed() ) ; let mut result = vec![]; loop { if let Some(item) = iter.next().unwrap().await { result.push(item); } else { break; } } assert_eq!(result, [0, 2, 4]);