Using the Java 8 Stream
API, I would like to register a "completion hook", along the lines of:
Stream<String> stream = Stream.of("a", "b", "c");
// additional filters / mappings that I don't control
stream.onComplete((Completion c) -> {
// This is what I'd like to do:
closeResources();
// This might also be useful:
Optional<Throwable> exception = c.exception();
exception.ifPresent(e -> throw new ExceptionWrapper(e));
});
The reason why I want to do that is because I want to wrap a resource in a Stream
for API clients to consume, and I want that Stream
to clean up the resource automatically once it is consumed. If that were possible, then the client could call:
Collected collectedInOneGo =
Utility.something()
.niceLookingSQLDSL()
.moreDSLFeatures()
.stream()
.filter(a -> true)
.map(c -> c)
.collect(collector);
Rather than what's needed currently:
try (Stream<X> meh = Utility.something()
.niceLookingSQLDSL()
.moreDSLFeatures()
.stream()) {
Collected collectedWithUglySyntacticDissonance =
meh.filter(a -> true)
.map(c -> c)
.collect(collector);
}
Ideally, I'd like to get into the java.util.stream.ReferencePipeline
's various methods, such as:
@Override
final void forEachWithCancel(Spliterator<P_OUT> spliterator, Sink<P_OUT> sink) {
try {
// Existing loop
do { } while (!sink.cancellationRequested() && spliterator.tryAdvance(sink));
}
// These would be nice:
catch (Throwable t) {
completion.onFailure(t);
}
finally {
completion.onSuccess();
}
}
Is there an easy way to do this with existing JDK 8 API?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…