@@ -219,6 +219,26 @@ where
219
219
} )
220
220
}
221
221
222
+ /// Do something with each item of this stream, afterwards passing it on.
223
+ ///
224
+ /// This is similar to the `Iterator::inspect` method in the standard
225
+ /// library where it allows easily inspecting each value as it passes
226
+ /// through the stream, for example to debug what's going on.
227
+ pub fn inspect < St , F > ( stream : St , f : F ) -> impl Stream < Item = St :: Item >
228
+ where
229
+ St : Stream ,
230
+ F : FnMut ( & St :: Item ) ,
231
+ {
232
+ let stream = Box :: pin ( stream) ;
233
+ crate :: stream:: unfold ( ( stream, f) , |( mut stream, mut f) | async {
234
+ let item = next ( & mut stream) . await ;
235
+ item. map ( |item| {
236
+ f ( & item) ;
237
+ ( item, ( stream, f) )
238
+ } )
239
+ } )
240
+ }
241
+
222
242
/// Converts this stream into a future of `(next_item, tail_of_stream)`.
223
243
/// If the stream terminates, then the next item is [`None`].
224
244
///
@@ -932,6 +952,19 @@ mod tests {
932
952
) ;
933
953
}
934
954
955
+ #[ test]
956
+ fn test_inspect ( ) {
957
+ let mut seen = Vec :: new ( ) ;
958
+ let stream = iter ( 1 ..=3 ) ;
959
+ let stream = inspect ( stream, |x| seen. push ( * x) ) ;
960
+
961
+ assert_eq ! (
962
+ vec![ 1 , 2 , 3 ] ,
963
+ executor:: block_on( collect:: <_, Vec <_>>( stream) )
964
+ ) ;
965
+ assert_eq ! ( seen, [ 1 , 2 , 3 ] ) ;
966
+ }
967
+
935
968
#[ test]
936
969
fn test_into_future ( ) {
937
970
let stream = iter ( 1 ..=2 ) ;
0 commit comments