toStream() converts a KTable’s update stream into a KStream of events. This lets aggregation results continue through stream operators or reach an output topic. section 7.2.1 section 8.2
Use the conversion when a table result needs stream-oriented processing:
- Print or inspect table contents with print() or peek(); KTable does not provide these methods directly. section 8.1.2 section 9.1.6
- Forward aggregation updates to downstream operators and sink topics. section 7.2.1
- Continue windowed results with operations such as map(), then expose or reshape the window key and value. section 9.1.6
- Expect stateful results to be forwarded when Kafka Streams flushes its cache, rather than necessarily after every intermediate update. section 7.2.1
Inspecting a windowed aggregation
iotHeatSensorStream.groupByKey()\n .windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(1)))\n .aggregate(() -> new IotSensorAggregation(tempThreshold), aggregator,\n Materialized.with(stringSerde, aggregationSerde))\n .toStream()\n .peek((windowedKey, aggregation) -> {\n Window window = windowedKey.window();\n LOG.info("Window started {} ended {} with value {}",\n window.startTime(), window.endTime(), aggregation);\n });\n\nThe aggregation produces a KTable; toStream() makes its windowed updates available to peek().
Listing 8.1 KTable and KStream printing to the console
KTable<String, StockTickerData> stockTickerTable =
builder.table(STOCK_TICKER_TABLE_TOPIC); #1
KStream<String, StockTickerData> stockTickerStream =
builder.stream(STOCK_TICKER_STREAM_TOPIC); #2
stockTickerTable.toStream()
.print(Printed.<String, StockTickerData>toSysOut()
.withLabel("Stocks-KTable")); #3
stockTickerStream
.print(Printed.<String, StockTickerData>toSysOut()
.withLabel("Stocks-KStream")); #4
Compare identical records through KTable and KStream printing: the KStream shows each record, while the KTable reflects updates and prints the latest state. section 8.1.2
