=doc graphstage sink example (#20955) (#21030)

This commit is contained in:
Stefano Bonetti 2016-07-26 11:20:08 +01:00 committed by Konrad Malawski
parent 867131f626
commit fb1905870c
4 changed files with 89 additions and 3 deletions

View file

@ -95,6 +95,40 @@ public class GraphStageDocTest extends AbstractJavaTest {
}
//#simple-source
//#simple-sink
public class StdoutSink extends GraphStage<SinkShape<Integer>> {
public final Inlet<Integer> in = Inlet.create("StdoutSink.in");
private final SinkShape<Integer> shape = SinkShape.of(in);
@Override
public SinkShape<Integer> shape() {
return shape;
}
@Override
public GraphStageLogic createLogic(Attributes inheritedAttributes) {
return new GraphStageLogic(shape()) {
// This requests one element at the Sink startup.
@Override
public void preStart() {
pull(in);
}
{
setHandler(in, new AbstractInHandler() {
@Override
public void onPush() throws Exception {
Integer element = grab(in);
System.out.println(element);
pull(in);
}
});
}
};
}
}
//#simple-sink
@Test
public void demonstrateCustomSourceUsage() throws Exception {
@ -116,6 +150,14 @@ public class GraphStageDocTest extends AbstractJavaTest {
assertEquals(result2.toCompletableFuture().get(3, TimeUnit.SECONDS), (Integer) 5050);
}
@Test
public void demonstrateCustomSinkUsage() throws Exception {
Graph<SinkShape<Integer>, NotUsed> sinkGraph = new StdoutSink();
Sink<Integer, NotUsed> mySink = Sink.fromGraph(sinkGraph);
Source.from(Arrays.asList(1, 2, 3)).runWith(mySink, mat);
}
//#one-to-one
public class Map<A, B> extends GraphStage<FlowShape<A, B>> {

View file

@ -58,6 +58,14 @@ source as any other built-in one:
.. includecode:: ../code/docs/stream/GraphStageDocTest.java#simple-source-usage
Similarly, to create a custom :class:`Sink` one can register a subclass :class:`InHandler` with the stage :class:`Inlet`.
The ``onPush()`` callback is used to signal the handler a new element has been pushed to the stage,
and can hence be grabbed and used. ``onPush()`` can be overridden to provide custom behaviour.
Please note, most Sinks would need to request upstream elements as soon as they are created: this can be
done by calling ``pull(inlet)`` in the ``preStart()`` callback.
.. includecode:: ../code/docs/stream/GraphStageDocTest.java#simple-sink
Port states, AbstractInHandler and AbstractOutHandler
-----------------------------------------------------