@@ -73,6 +73,18 @@ public class MoreStreamsTest {
7373 .containsExactly (1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 );
7474 }
7575
76+ @ Test public void generate_closesConsumedFanoutStreams () {
77+ List <String > closed = new ArrayList <>();
78+ assertThat (MoreStreams .generate (
79+ 1 ,
80+ i -> i == 1
81+ ? Stream .of (2 , 3 ).onClose (() -> closed .add ("fanout" ))
82+ : Stream .empty ())
83+ .collect (toList ()))
84+ .containsExactly (1 , 2 , 3 ).inOrder ();
85+ assertThat (closed ).containsExactly ("fanout" );
86+ }
87+
7688 @ Test public void generateInfiniteStreamWithGuavaIterablesLimit () throws Exception {
7789 Stream <Integer > generated = MoreStreams .generate (1 , i -> Stream .of (i + 1 ));
7890 assertThat (Iterables .limit (MoreStreams .iterateOnce (generated ), 5 ))
@@ -255,6 +267,30 @@ public class MoreStreamsTest {
255267 assertThat (list ).containsExactly (1 , 3 ).inOrder ();;
256268 }
257269
270+ @ Test public void withSideEffect_closesInputWithoutTraversal () {
271+ List <String > closed = new ArrayList <>();
272+ List <Integer > seen = new ArrayList <>();
273+ Stream <Integer > stream = MoreStreams .withSideEffect (
274+ Stream .of (1 , 2 ).onClose (() -> closed .add ("input" )), seen ::add );
275+ assertThat (closed ).isEmpty ();
276+ stream .close ();
277+ stream .close ();
278+ assertThat (closed ).containsExactly ("input" );
279+ assertThat (seen ).isEmpty ();
280+ }
281+
282+ @ Test public void withSideEffect_closesInputAfterShortCircuit () {
283+ List <String > closed = new ArrayList <>();
284+ List <Integer > seen = new ArrayList <>();
285+ try (Stream <Integer > stream = MoreStreams .withSideEffect (
286+ Stream .of (1 , 2 ).onClose (() -> closed .add ("input" )), seen ::add )) {
287+ assertThat (stream .limit (1 ).collect (toList ())).containsExactly (1 );
288+ assertThat (closed ).isEmpty ();
289+ }
290+ assertThat (closed ).containsExactly ("input" );
291+ assertThat (seen ).containsExactly (1 );
292+ }
293+
258294 @ Test public void withSideEffect_lateBinding () {
259295 List <Integer > source = new ArrayList <>();
260296 List <Integer > list = new ArrayList <>();
0 commit comments