StreamConverters.asInputStream

Create a sink which materializes into an InputStream that can be read to trigger demand through the sink.

Additional Sink and Source converters

Signature

StreamConverters.asInputStreamStreamConverters.asInputStream

Description

Create a sink which materializes into an InputStream that can be read to trigger demand through the sink. Bytes emitted through the stream will be available for reading through the InputStream

The InputStream will be ended when the stream flowing into this Sink completes, and the closing the InputStream will cancel the inflow of this Sink.

Reactive Streams semantics

cancels when the InputStream is closed

backpressures when no read is pending on the InputStream

Example

Here is an example of a SinkSink that reads the contents from the source, converts it into uppercase and materializes into a java.io.InputStream

Scala
sourceval toUpperCase: Flow[ByteString, ByteString, NotUsed] = Flow[ByteString].map(_.map(_.toChar.toUpper.toByte))
val source: Source[ByteString, NotUsed] = Source.single(ByteString("some random input"))
val sink: Sink[ByteString, InputStream] = StreamConverters.asInputStream()

val inputStream: InputStream = source.via(toUpperCase).runWith(sink)
Java
sourceCharset charset = Charset.defaultCharset();
Flow<ByteString, ByteString, NotUsed> toUpperCase =
    Flow.<ByteString>create()
        .map(
            bs -> {
              String str = bs.decodeString(charset).toUpperCase();
              return ByteString.fromString(str, charset);
            });

final Sink<ByteString, InputStream> sink = StreamConverters.asInputStream();
final InputStream stream =
    Source.single(ByteString.fromString("Some random input"))
        .via(toUpperCase)
        .runWith(sink, system);