Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Flux.unfold #3897

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions reactor-core/src/main/java/reactor/core/publisher/Flux.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.Spliterator;
Expand Down Expand Up @@ -2073,6 +2074,30 @@ public static <T> Flux<T> switchOnNext(Publisher<? extends Publisher<? extends T
Queues.unbounded(prefetch), prefetch));
}

/**
* Creates a {@link Flux} that uses a function `f` to produce elements of type `T`
* and update an internal state of type `S`.
*
* @param init State initial value
* @param f Computes the next element (or returns empty {@link Optional} to signal the end of the sequence)
* @param <T> Type of the elements
* @param <S> Type of the internal state
*
* @return a {@link Flux} that produces elements using `f` until `f` returns empty {@link Optional}
*/
public static <T, S> Flux<T> unfold(S init, Function<S, Optional<Tuple2<T, S>>> f) {
return Flux.generate(() -> init, (s, sink) -> {
Optional<Tuple2<T, S>> res = f.apply(s);
if (!res.isPresent()) {
sink.complete();
return s;
} else {
sink.next(res.get().getT1());
return res.get().getT2();
}
});
}

/**
* Uses a resource, generated by a supplier for each individual Subscriber, while streaming the values from a
* Publisher derived from the same resource and makes sure the resource is released if the sequence terminates or
Expand Down