Advanced Features: Connecting VStream to Other APIs
Bridge a stream to optics, Flow.Publisher, List, Stream and Paths, or run it without a VTask.
- Change a field of every element in a list or a stream with a
StreamTraversal, reading a stream only as far as the consumer pulls - Hand a stream to a
Flow.Subscriber, and read aFlow.Publisheras a stream - Convert between
VStream,Listand Java'sStream, and move a Path between them with aNatural - Find a Path for a
KindwithPath.from, and register a provider of your own - Get a stream's answer directly, with no
VTaskto run, throughVStreamContext
The code on this page is VStreamAdvancedBook.java: the page includes it, so the build compiles and runs it. VStreamAdvancedBookTest.java holds what the page says each method does.
Each section stands alone: optics over a stream, a Flow.Publisher, List and Stream, answers without a VTask, and, for code that builds Paths generically, Path.from.
The code on this page uses the order feed from the VStream page. VStreamBook.PagedFeed is a feed that records each page it is asked for, and VStreamBook.orders(feed) is the stream of its orders. customer and paid read an order. These are the page's imports:
import static org.higherkindedj.hkt.instances.Witnesses.list;
import static org.higherkindedj.hkt.instances.Witnesses.vstream;
import static org.higherkindedj.hkt.list.ListKindHelper.LIST;
import static org.higherkindedj.hkt.vstream.VStreamKindHelper.VSTREAM;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Flow;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.example.book.optics.cast.LineItemLenses;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.example.book.optics.cast.OrderLenses;
import org.higherkindedj.example.book.optics.cast.OrderStatus;
import org.higherkindedj.hkt.Natural;
import org.higherkindedj.hkt.effect.GenericPath;
import org.higherkindedj.hkt.effect.Path;
import org.higherkindedj.hkt.effect.VStreamTransformations;
import org.higherkindedj.hkt.effect.capability.Chainable;
import org.higherkindedj.hkt.effect.context.VStreamContext;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.vstream.VStream;
import org.higherkindedj.hkt.vstream.VStreamKind;
import org.higherkindedj.hkt.vstream.VStreamReactive;
import org.higherkindedj.optics.Traversal;
import org.higherkindedj.optics.extensions.StreamTraversal;
import org.higherkindedj.optics.util.Traversals;
Optics over a stream
To change one field of every element a list or a stream gives, such as each order's status, use a StreamTraversal. Like a Traversal from the Optics chapter, it reaches every focus in a structure. A Traversal reads them all at once, through an Applicative. A StreamTraversal gives them as a VStream, so over a stream it reads only as far as the consumer pulls.
forList() focuses on each element of a list, and andThen with a Lens narrows each focus to one field, here an order line's price:
// A lamp, and four bulbs
static final List<LineItem> LINES =
List.of(
new LineItem("LAMP", 1, new BigDecimal("40.00")),
new LineItem("BULB", 4, new BigDecimal("2.50")));
// Every price in an order's lines
static final StreamTraversal<List<LineItem>, BigDecimal> PRICES =
StreamTraversal.<LineItem>forList().andThen(LineItemLenses.price());
static BigDecimal withTenPercent(BigDecimal price) {
return price.multiply(new BigDecimal("1.10")).setScale(2, RoundingMode.HALF_UP);
}
List<BigDecimal> prices = PRICES.stream(LINES).toList().run();
// [40.00, 2.50]
List<LineItem> raised = PRICES.modify(VStreamAdvancedBook::withTenPercent, LINES);
BigDecimal lampPrice = raised.getFirst().price();
// 44.00
forVStream() focuses on each element of a stream, so with OrderLenses.status() it reaches the status of every order the feed gives:
// The status of every order a stream gives
static final StreamTraversal<VStream<Order>, OrderStatus> STATUSES =
StreamTraversal.<Order>forVStream().andThen(OrderLenses.status());
// A new order counts as paid, here
static OrderStatus markPaid(OrderStatus status) {
return status == OrderStatus.NEW ? OrderStatus.PAID : status;
}
VStreamBook.PagedFeed feed = new VStreamBook.PagedFeed(ORDERS);
VStream<Order> allPaid =
STATUSES.modify(VStreamAdvancedBook::markPaid, VStreamBook.orders(feed));
List<OrderStatus> firstTwo = allPaid.take(2).map(Order::status).toList().run();
// [PAID, PAID]
List<Integer> pagesFetched = feed.fetched();
// [1]
Over a stream, modify gives a new stream, which changes each element as it is pulled. Two orders are taken, so only the feed's first page is fetched, and Grace's order, which was new, comes out paid. An endless stream works the same way. Written by hand, this is orders.map(order -> OrderLenses.status().modify(...)). A StreamTraversal is one value that serves a list or a stream, composes with lenses, and converts to a Traversal.
modifyVTask changes each focus with a task, and starts no thread of its own. Over a list, it returns one task that runs the element tasks in turn. Over a stream, that task gives the new stream at once, and each element's task runs as the element is pulled, on the thread that pulls it.
Traversal | StreamTraversal | |
|---|---|---|
| Reads the focuses | All at once, through an Applicative | As a VStream; from forVStream(), as the consumer pulls |
| An endless stream | Never finishes reading it | From forVStream(), stream, modify and modifyVTask read it as pulled |
| Effects | Any Applicative | VTask |
Converting to a Traversal
toTraversal() gives a Traversal for code that takes one, such as Traversals.getAll:
Traversal<List<LineItem>, BigDecimal> asTraversal = PRICES.toTraversal();
BigDecimal unitPrices =
Traversals.getAll(asTraversal, LINES).stream().reduce(BigDecimal.ZERO, BigDecimal::add);
// 42.50
getAll gives the two unit prices, which sum to 42.50. Over a stream, the Traversal reads the stream once, and the stream Traversals.modify gives can be read again. StreamTraversal.fromTraversal(traversal) goes the other way, and reads every focus as soon as stream is called.
Exchanging elements with a Flow.Publisher
Java's Flow.Publisher sends elements to a subscriber as fast as the subscriber asks for them, which is how reactive libraries hand data on. A VStream is pulled instead. VStreamReactive joins the two.
VStream to Publisher
VStreamReactive.toPublisher(stream) gives a publisher that pulls an element only when its subscriber has asked for one, plus one more to notice the end of the stream. Each subscriber reads the stream from the start. When a subscriber cancels, or the stream fails, the publisher closes what is left of the stream, so its finalisers run. A subscriber that cancels before it asks for anything closes nothing, since it has read nothing.
Publisher to VStream
VStreamReactive.fromPublisher(publisher, bufferSize) reads a publisher as a stream. Here the stream of customers goes out through a publisher and is read back:
VStream<String> customers = VStream.fromList(ORDERS).map(VStreamBook::customer);
Flow.Publisher<String> publisher = VStreamReactive.toPublisher(customers);
VStream<String> readBack = VStreamReactive.fromPublisher(publisher, 16);
List<String> firstThree = readBack.take(3).toList().run();
// [Ada, Grace, Alan]
- Each run subscribes at its first pull, so building the stream subscribes nothing, and a stream read twice subscribes twice.
- A hot publisher, such as a
SubmissionPublisher, sends a run only what it publishes after the run subscribes. Publish oncegetNumberOfSubscribers()shows the run has subscribed. - Incoming elements are held in a buffer of
bufferSize, 256 if you leave it out. The stream first asks for that many, then for one more as it takes each element. - A run that stops early cancels its subscription, so
take(3)stops the publisher once it has its three elements.
The Flow rules forbid a null element, and so does a VStream. A publisher that sends one has its subscription cancelled, and the stream fails with a NullPointerException: VStream.fromPublisher element cannot be null.
On a VStreamPath, Path.vstreamFromPublisher(publisher, bufferSize) reads a publisher, and path.toPublisher() hands the stream to one.
Converting between VStream, List and Stream
For one stream, toList().run() gives a List. VStreamTransformations is for code written over Kind, which takes a conversion as a value. It gives a Natural for each direction between VStream and List, and between VStream and Java's Stream. A Natural converts one container to another whatever its elements, and GenericPath.mapK takes one, to move a path onto another container. The Foundations introduction's "Which level am I working at?" tip says when code works over Kind.
Natural<ListKind.Witness, VStreamKind.Witness> listToVStream =
VStreamTransformations.listToVStream();
Natural<VStreamKind.Witness, ListKind.Witness> vstreamToList =
VStreamTransformations.vstreamToList();
GenericPath<ListKind.Witness, Order> asList =
GenericPath.of(LIST.widen(ORDERS), Instances.monad(list()));
GenericPath<VStreamKind.Witness, Order> asStream =
asList.mapK(listToVStream, Instances.monad(vstream()));
long paid = VSTREAM.narrow(asStream.runKind()).filter(VStreamBook::paid).count().run();
// 4
List<Order> roundTrip =
LIST.narrow(listToVStream.andThen(vstreamToList).apply(LIST.widen(ORDERS)));
int orders = roundTrip.size();
// 6
listToVStream and streamToVStream read nothing until the stream is pulled. vstreamToList and vstreamToStream read the whole stream when they are applied, on the calling thread, so take a prefix of an endless stream first. A Java Stream can be read only once, so each run of a VStream made from one carries on from where the last run stopped. streamToVStream builds it with fromStream, which closes the Java Stream when a run is over, so a later run over a file can fail, as A file, a line at a time says.
Finding a Path, and registering a provider
Path.from(kind, witness) asks the PathProvider registered for witness for a Path that holds kind. VStreamPathProvider answers for a VStream:
Optional<Chainable<?, Order>> found =
Path.from(VSTREAM.widen(VStream.fromList(ORDERS)), VStreamKind.Witness.class);
boolean hasPath = found.isPresent();
// true
The registry cannot know which Path a provider builds, so the result's family is open, the ? in Chainable<?, Order>. It can be mapped, but via and zipWith accept no step. To chain, build the Path directly with Path.vstream(...).
The provider is registered in META-INF/services/org.higherkindedj.hkt.effect.spi.PathProvider and in the provides clause of hkj-core's module-info, so Path.from() finds it whether hkj-core is on the classpath or the module path. To register a PathProvider of your own, list it in the same services file, which ServiceLoader reads when the jar is on the classpath. In a module with a module-info, also declare provides org.higherkindedj.hkt.effect.spi.PathProvider with ...;, which is all it reads on the module path.
A provider whose effect can fail overrides monadError() to return its MonadError in an Optional. The default is empty, as for VStream, and supportsRecovery() returns whether one is present. PathRegistry, which holds the providers, gives the one it removed from unregister in an Optional too.
Answers without a VTask: VStreamContext
A VStream's terminal operations, such as toList, give a VTask to run. A VStreamContext runs the stream itself, on the calling thread, and returns the answer. It works like the Effect Contexts, such as VTaskContext, and has many of a VStream's operations: map, via, filter, take, parEvalMap and chunk among them:
List<String> firstPaid =
VStreamContext.fromList(ORDERS)
.filter(VStreamBook::paid)
.map(VStreamBook::customer)
.take(3)
.toList();
// [Ada, Alan, Edsger]
long shipped =
VStreamContext.fromList(ORDERS)
.filter(order -> order.status() == OrderStatus.SHIPPED)
.count();
// 1
A stream that fails throws from the terminal operation, with a checked exception wrapped in a VTaskExecutionException. toVStream() and toPath() give the stream, and a VStreamPath over it, when you need them.
Methods
| Method | What it does |
|---|---|
StreamTraversal.forList(), forVStream() | Focuses on each element of a list, or of a stream |
streamTraversal.andThen(lens), andThen(other) | Narrows each focus to a field, or to another StreamTraversal's focuses |
streamTraversal.stream(source) | Gives the focuses as a VStream |
streamTraversal.modify(f, source) | Changes each focus with f |
streamTraversal.modifyVTask(f, source) | Changes each focus with a task |
streamTraversal.toTraversal(), StreamTraversal.fromTraversal(traversal) | Converts to and from a Traversal |
VStreamReactive.toPublisher(stream) | Hands the stream to each subscriber that asks |
VStreamReactive.fromPublisher(publisher, bufferSize), fromPublisher(publisher) | Reads a publisher as a stream, holding up to bufferSize elements, or 256 |
Path.vstreamFromPublisher(publisher, bufferSize), vstreamPath.toPublisher() | Do the same on a VStreamPath |
VStreamTransformations.listToVStream(), vstreamToList(), streamToVStream(), vstreamToStream() | Give the Naturals between VStream, List and Stream |
genericPath.mapK(natural, monad) | Moves a path onto another container |
Path.from(kind, witness) | Finds a Path for kind through the provider registered for witness |
VStreamContext.fromList(list), of(stream), range(from, to) | Start a context |
context.map(f), via(f), filter(p), take(n) | Build the next context |
context.toList(), count(), fold(identity, op), find(p) | Run the stream, and give the answer |
context.toVStream(), toPath() | Give the stream, or a VStreamPath over it |
When to use each bridge
| You need | Use |
|---|---|
| One field of every element changed, in a list or a stream | StreamTraversal, with a Lens |
| Elements from a reactive library, or handed to one | VStreamReactive |
A VStream's elements as a List or a Stream, or the other way | toList(), or VStreamTransformations for code over Kind |
A stream's answer with no VTask to run | VStreamContext |
A Path for a Kind your code cannot name | Path.from, or Path.vstream to chain |
| Every focus of a structure in memory, read at once | A Traversal |
Practise StreamTraversal, the publisher bridge, the transformations and VStreamContext in Parts 2 to 5 of TutorialVStreamAdvanced (exercises 4 to 12), and optics over a VStream in Tutorial 17: VStream Optics (8 exercises).
Previous: Resource-Safe Streaming Next: Reader