<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tomasz Kiełbowicz on Medium]]></title>
        <description><![CDATA[Stories by Tomasz Kiełbowicz on Medium]]></description>
        <link>https://medium.com/@tomasz.kielbowicz?source=rss-7c0ac91da60e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uJ-6y3P2DGleak4x</url>
            <title>Stories by Tomasz Kiełbowicz on Medium</title>
            <link>https://medium.com/@tomasz.kielbowicz?source=rss-7c0ac91da60e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:46:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomasz.kielbowicz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use Google’s Speech-to-Text in a web application. Working example.]]></title>
            <link>https://blog.softwaremill.com/how-to-use-googles-speech-to-text-in-a-web-application-working-example-a4b64c61f133?source=rss-7c0ac91da60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4b64c61f133</guid>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[voice-recognition]]></category>
            <category><![CDATA[speech-to-text-api]]></category>
            <dc:creator><![CDATA[Tomasz Kiełbowicz]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 08:21:30 GMT</pubDate>
            <atom:updated>2021-01-04T15:02:13.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Google’s Speech-to-Text in a web application. A working example.</h3><h3>What is Speech-to-Text</h3><p><a href="https://cloud.google.com/speech-to-text">Google’s Speech-to-Text (STT) API</a> is an easy way to integrate voice recognition into your application. The idea of the service is straightforward, it receives an audio stream and responds with recognized text. As of the time of writing the first 60 minutes of speech recognition each month are free of charge, so you can give it a try without any costs. Each minute over the limit costs about $0.006, the time is rounded up to 15 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJvq-1iKtQhF4aEVAwZW8g.png" /></figure><h3>Prerequisites</h3><p>To follow this tutorial you have to enable Speech-to-Text:</p><ol><li>Open GCP console <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></li><li>Select or create a new project</li><li>Search for “Cloud Speech-to-Text API” and enable it</li><li>Search for “Service accounts” and create a new service account</li><li>Add a key to the service account, choose JSON format, download and safely save the key file</li></ol><h3>Overview</h3><p>It is possible to send the audio stream directly from the browser, but as far as I know, there is no way to authorize the client (browser) to use our account without exposing the service credentials. Therefore we are going to send an audio stream from the browser via web socket to the backend and then redirect it to the STT and send back the response.</p><p>At the client side we’re using Typescript without additional dependencies, and at the backend, it will be <a href="https://http4s.org/">http4s</a> configured with <a href="https://github.com/softwaremill/tapir">tapir</a>. For STT calls we’ll use the library provided by Google.</p><h3>Speech-to-Text API</h3><p>The API is the central point of our solution, so first we have to understand how we can use the service and what requirements or restrictions it implies on the rest of the solution.</p><p>The documentation describes 3 typical usage scenarios: short file transcription, long file transcription, and the transcription of audio streaming input. We are interested in the 3rd scenario as we want to recognize a user’s speech on the fly.</p><p>To achieve the best result of voice recognition the documentation <a href="https://cloud.google.com/speech-to-text/docs/best-practices">recommends</a> the following features of the audio stream:</p><ul><li>sampling at 16 kHz</li><li>16-bit signed sample format</li><li>lossless compression</li><li>single channel</li><li>100 ms length of the audio chunk in each request in the stream</li></ul><p>Also any pre-processing like gain control, noise reduction, or resampling is discouraged.</p><h3>Web browser</h3><p>The common choice for audio (and video) capture in a browser is <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API">MediaStream Recording API</a>. Unfortunately, it supports only compressed formats, and worse, supported formats depend on the browser and platform. The better choice is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a>, which can be used for custom audio stream processing. Both technologies are built on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams</a> that provides access to the client’s audio devices.</p><p>First, we have to obtain a handle for the audio stream of the user’s microphone using Media Capture and Streams API:</p><pre>const sampleRate = 16000</pre><pre>const stream = navigator.mediaDevices.getUserMedia({<br>  audio: {<br>    deviceId: &quot;default&quot;,<br>    sampleRate: sampleRate,<br>    sampleSize: 16,<br>    channelCount: 1<br>  },<br>  video: false<br>})</pre><p>Here we use the “default” device, though it’s possible to enumerate available devices and select the specific one. We also set the required parameters of the stream.</p><p>Next, we are going to process the stream with the Web Audio API. This API allows us to build a network of audio processing nodes. The API provides a set of nodes for common processing tasks. We are interested in two of them:</p><ul><li><strong>MediaStreamAudioSourceNode</strong> — connects a media stream to the network</li><li><strong>AudioWorkletNode</strong> — allows custom processing of the audio stream</li></ul><p>All nodes exist in AudioContext which we have to create first:</p><pre>const audioContext = new window.AudioContext({sampleRate: sampleRate})</pre><p>Then we can create MediaStreamAudioSourceNode from the stream obtained earlier:</p><pre>const source: MediaStreamAudioSourceNode = audioContext.createMediaStreamSource(stream)</pre><p>The creation of the worklet node is a bit more complicated. The worklet node has to perform its job in a separate thread. To achieve that the Web Audio API utilizes the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker API</a>. Fortunately, the API handles most of the process. We have to do 2 things:</p><ul><li>create the processing script and register it under a name</li><li>create the worklet node in the main context using the registered name</li></ul><h3>Audio stream processing</h3><p>Our processing node is responsible for 2 tasks:</p><ul><li>transcoding of the stream</li><li>combining frames into 100 ms audio chunks</li></ul><p>Nodes of the Web Audio API process the audio stream in frames of the length of 128 samples. Such a frame is called by the specification the <strong>render quantum</strong>. Each sample is represented by a 32-bit floating number, so the transcoding is simply a remapping of a 32-bit float sample to a 16-bit signed sample.</p><p>The full source of the processing script:</p><pre>const quantumSize = 128<br><br>class TestProcessor extends AudioWorkletProcessor {<br>  constructor(options) {<br>    super()<br>    this.quantaPerFrame = 12<br>    this.quantaCount = 0<br>    this.frame = new Int16Array(quantumSize * this.quantaPerFrame)<br>  }<br><br>  process(inputs, outputs, parameters) {<br>    const offset = quantumSize * this.quantaCount<br>    inputs[0][0].forEach((sample, idx) =&gt; this.frame[offset + idx] = Math.floor(sample * 0x7fff))<br>    this.quantaCount = this.quantaCount + 1<br>    if (this.quantaCount === this.quantaPerFrame) {<br>      this.port.postMessage(this.frame)<br>      this.quantaCount = 0<br>    }<br>    return true<br>  }<br>}<br><br>registerProcessor(&#39;pcm-worker&#39;, TestProcessor)</pre><p>The number of rendering quanta in each stream chunk is 12, so the length of the chunk will be: <em>(1/16 kHz)*128*12 = 96 ms.</em></p><p>The 32-bit float number sample is in the range <em>(-1;1)</em>. We need a number in the range <em>(-32,768;32,767)</em>. To transcode we need to multiply the input sample by 32,768 and round the result: <em>Math.floor(sample * 0x7fff).</em></p><p>After the full chunk is completed it is sent to the main context by the worker’s port: <strong>this.port.postMessage(this.frame)</strong>. We will soon see how it is received at the other end.</p><p>Before we create the worklet node we have to register the worklet script into our audio context:</p><pre>audioContext.audioWorklet.addModule(&#39;/pcmWorker.js&#39;)</pre><p>Now we can create the worklet node in the main thread and connect it with the stream audio source node:</p><pre>const pcmWorker = new AudioWorkletNode(audioContext, &#39;pcm-worker&#39;, {<br>  outputChannelCount: [1]<br>})<br>source.connect(pcmWorker)</pre><h3>WebSocket</h3><p>To route the audio stream from the worklet node to the backend we have to make a WebSocket connection:</p><pre>const conn = new WebSocket(&quot;ws://localhost:8080/ws/stt&quot;)</pre><p>and then we can redirect the audio stream from the PCM worker to the connection (we use AudioWorkletNode’s port to receive data from the processing script):</p><pre>pcmWorker.port.onmessage = event =&gt; conn.send(event.data)<br>pcmWorker.port.start()</pre><h3>Backend</h3><p>We will start backend implementation with the WebSocket endpoint. Definition of the endpoint in <a href="https://tapir.softwaremill.com/en/latest/endpoint/websockets.html">tapir</a>:</p><pre>val <em>wsEndpoint </em>=<br>  <em>endpoint</em>.get<br>    .in(&quot;stt&quot;)<br>    .out(webSocketBody[WebSocketFrame, CodecFormat.TextPlain, WebSocketFrame, CodecFormat.TextPlain](<em>Fs2Streams</em>[Task]))</pre><p>to create http4s route we have to provide <strong>handleWebSocket</strong> <a href="https://fs2.io/">fs2</a> Pipe transforming the input stream of <strong>WebSocketFrame</strong> into the output stream of <strong>WebSocketFrame</strong>:</p><pre><em>wsEndpoint</em>.toRoutes(_ =&gt; Task.<em>pure</em>(<em>Right</em>(handleWebSocket)))</pre><p>Before we start sending the audio stream to STT we have to create the <strong>SpeechClient</strong> and establish the gRPC connection:</p><pre>val <em>speechClient = </em>SpeechClient.<em>create<br>val sttStream = <br>speechClient</em>.streamingRecognizeCallable.splitCall(new RecognitionObserver(queue))</pre><p>Our <strong>RecognitionObserver</strong> will receive the response from STT and push it to the fs2 Queue after conversing to the simple JSON:</p><pre>class RecognitionObserver(queue: Queue[Task, String]) extends ResponseObserver[StreamingRecognizeResponse] {<br><br>  override def onResponse(response: StreamingRecognizeResponse) = {<br>    val result = response.getResultsList.get(0)<br>    val isFinal = result.getIsFinal<br>    val transcript = result.getAlternativesList.get(0).getTranscript<br>    val msg = s&quot;&quot;&quot;{&quot;final&quot;: <strong>$</strong>isFinal, &quot;text&quot; : &quot;<strong>$</strong>transcript&quot;}&quot;&quot;&quot;<br>    queue.enqueue1(msg).runSyncUnsafe()<br>  }<br><br>  override def onError(t: Throwable): Unit = {}<br>  override def onComplete(): Unit = {}<br>  override def onStart(controller: StreamController): Unit = {}<br>}</pre><p>The first message sent to STT after connecting has to be the configuration. We have to provide parameters of the audio stream (encoding and sample rate) and we can configure some parameters of the recognition process like recognition <a href="https://cloud.google.com/speech-to-text/docs/basics#select-model">model</a>, the <a href="https://cloud.google.com/speech-to-text/docs/languages">language</a>, or whether we want to receive interim results:</p><pre>object SpeechRecognitionConfig {<br>  private val <em>recognitionConfig </em>= RecognitionConfig.<em>newBuilder<br>    </em>.setEncoding(RecognitionConfig.AudioEncoding.<em>LINEAR16</em>)<br>    .setLanguageCode(&quot;en_US&quot;)<br>    .setSampleRateHertz(16000)<br>    .setModel(&quot;command_and_search&quot;)<br>    .build<br><br>  def apply(): StreamingRecognitionConfig = StreamingRecognitionConfig.<em>newBuilder<br>    </em>.setConfig(<em>recognitionConfig</em>)<br>    .setInterimResults(true)<br>    .build<br><br>  val <em>configRequest</em>: StreamingRecognizeRequest = StreamingRecognizeRequest.<em>newBuilder<br></em>.setStreamingConfig(<em>SpeechRecognitionConfig</em>())<br>.build<br>}</pre><p>Sending of the configuration:</p><pre>sttStream.send(SpeechRecognitionConfig.<em>configRequest</em>)</pre><p>Then we can start sending audio stream chunks to the STT wrapping them into <strong>StreamingRecognizeRequest</strong>:</p><pre>private def sendAudio(sttStream: ClientStream[StreamingRecognizeRequest], data: Array[Byte]) =<br>  <em>Task</em>(StreamingRecognizeRequest.<em>newBuilder</em>.setAudioContent(ByteString.<em>copyFrom</em>(data)).build)<br>    .flatMap(req =&gt; <em>Task</em>(sttStream.send(req)))</pre><p>And finally, <strong>handleWebSocket</strong> Pipe that connects the <strong>WebSocket</strong> with STT stream:</p><pre>def handleWebSocket: Pipe[Task, WebSocketFrame, WebSocketFrame] = audioStream =&gt;<br>  for {<br>    queue &lt;- eval(unbounded[Task, String])<br>    sttStream &lt;- bracket(connectStt(queue))(stt =&gt; Task(stt.closeSend()))<br>    audioChunk &lt;- audioStream.collect {<br>      case binary: WebSocketFrame.Binary =&gt; binary.payload<br>    }<br>    sttResultStream = queue.dequeue<br>    transcript &lt;- eval(sendAudio(sttStream, audioChunk)).drain.mergeHaltBoth(sttResultStream)<br>  } yield WebSocketFrame.text(transcript)</pre><h3>Working example</h3><p>The working example can be found here: <a href="https://github.com/gobio/bootzooka-speech-to-text">https://github.com/gobio/bootzooka-speech-to-text</a></p><p>It’s based on SoftwareMill’s <a href="https://github.com/softwaremill/bootzooka">Bootzooka</a>, look at the <a href="https://softwaremill.github.io/bootzooka/">documentation</a> on how to start the application. Remember to set the <strong>GOOGLE_APPLICATION_CREDENTIALS</strong> environment variable pointing to the downloaded service account JSON key. The example contains only essential elements requires for it to work, specifically, it lacks the proper error handling.</p><p>All STT related changes were introduced with this <a href="https://github.com/gobio/bootzooka-speech-to-text/commit/5d4f6126c690043dd71c2d2715aa7ad2f5b0497a">commit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX2pQDD1Y0opEtCkY9kaFA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4b64c61f133" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/how-to-use-googles-speech-to-text-in-a-web-application-working-example-a4b64c61f133">How to use Google’s Speech-to-Text in a web application. Working example.</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why, when and how to return Stream from your Java API instead of a collection]]></title>
            <link>https://blog.softwaremill.com/why-when-and-how-to-return-stream-from-your-java-api-instead-of-a-collection-c30e7ebc5407?source=rss-7c0ac91da60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c30e7ebc5407</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomasz Kiełbowicz]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 08:08:53 GMT</pubDate>
            <atom:updated>2020-02-10T08:08:53.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDKT4WAfk4WVG_CJAXLsfQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jfobranco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joao Branco</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Collections are basic and commonly used data structures. Programmers from the beginning of their career learn how to use them to receive, process and return data. Getting more advanced in Java programming, they find stream() method to convert a collection into a stream and learn how to process data using some of the stream’s useful methods like map, flatMap or reduce. They could also notice that other APIs in Java return a stream too e.g. String.lines(), Matcher.results(), Files.find(), Random.ints().</p><p>If you have experience with consuming streams but haven’t produced them yet, this article is for you. I’m going to show you some scenarios where streams can be very convenient and examples on how to use them. Additionally, I shortly mention error handling and resource management.</p><p>The article is based on standard Java library java.util.stream. It’s related neither to<a href="https://www.reactive-streams.org/"> reactive streams</a> nor to other implementation of streams like e.g.<a href="https://www.vavr.io/"> Vavr</a>. Also, I’m not going to cover advanced details of streams like parallel execution.</p><p>First, let’s discuss briefly distinctive streams features compared to collections. Although there are some similarities, the differences are significant and you shouldn’t treat streams as just another type of collection in the library.</p><p>Accordingly to the<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/package-summary.html"> documentation</a> of java.util.stream the most important features are:</p><ul><li><strong>No storage</strong> and <strong>Possibly unbounded</strong> — collections are <strong>ready-to-use</strong> data structures, while stream represents <strong>the ability to produce the data</strong>, which usually doesn’t even exist at the point the stream is created. As data in streams are not stored we can create practically indefinite streams or rephrasing it more practically, we can let the consumer decide how many elements to read from the stream, keeping it potentially indefinite from producer perspective (e.g. new Random().ints()).</li><li><strong>Laziness-seeking</strong> — many operations (like filtering, mapping) are suspended at the time of stream definition and performed only when a consumer decides to consume data from a stream</li><li><strong>Functional in nature</strong> — as you already have some experience with consuming streams, you could notice that processing data in streams you create a new stream for each step like filter or map instead of modifying source data</li><li><strong>Consumable</strong> — you can read the stream only once, then it becomes “consumed” unlike collections which can be read many times</li></ul><p>Let’s now see what problems we can solve with streams.</p><h3>Processing a large volume of data</h3><p>Assume, we have to replicate data from an external service into our database. The volume of data to replicate can be arbitrarily large. We can’t fetch all data, store it in a collection and then save in the database because of the potential risk of running out of heap memory. We have to process data in batches and design an interface between an external service client and database storage. Because the stream doesn’t store the date it can be used to safely process the required amount of data.</p><h4>Example:</h4><p>In the example (and all following) we are going to use static methods of java.util.stream.Stream interface to build a stream. The most powerful and flexible way to build a stream in Java is to implement the Spliterator interface and then wrap it into a stream using StreamSupport class. Though, as we can see, static factory methods in the Stream interface are sufficient in many cases.</p><p>Assume a simple API to fetch data from an external service that supports pagination (e.g. rest service, database). The API fetches at most limit items starting from the offset. Using the API iteratively we can fetch as much data as required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d83e760c8123ec0a59b79afadb7322cb/href">https://medium.com/media/d83e760c8123ec0a59b79afadb7322cb/href</a></iframe><p>Now we can use the API to provide the stream of data and isolate an API’s consumer from the pagination API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613ff6275ffcf70684a852f2417af8c8/href">https://medium.com/media/613ff6275ffcf70684a852f2417af8c8/href</a></iframe><p>Where Cursor is a simple holder of the current offset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f9841f8d27c8034a12c3c0d39c39485/href">https://medium.com/media/8f9841f8d27c8034a12c3c0d39c39485/href</a></iframe><p>We use Stream.generate() method to build an infinite stream (7), where each element is created by the provided supplier. At this point, the stream elements are pages fetched from the REST API represented by List&lt;T&gt;. The instance of the Cursor class is created for each stream to track the progress of fetched elements. Stream.takeWhile() method (8) is used to detect the last page and finally to return the stream of T instead of List&lt;T&gt; we use flatMap to flatten the stream (9). Although in some scenarios it could be useful to preserve the batch e.g. to save the whole page in one transaction.</p><p>Now we can use the Service.stream(size, batchSize) to retrieve arbitrary long stream, without any knowledge of pagination API (we decided to expose the batchSize parameter, but it’s a design decision). The memory consumption, at any point in time, is limited by the batch size. A consumer can process the data one by one saving in the database or batch them again (with potentially different batch sizes).</p><h3>Fast access to (incomplete) data</h3><p>Assume we have a time-consuming operation which has to be performed on each element of data and the computation takes the time t. For n elements, the consumer has to wait for t * n before receiving the result of the computation. It could be an issue e.g. if a user is waiting for the table with the results of the computation. Preferably we would like to show the first results instantly as they are computed instead of waiting for computation of all results and filing the table at once.</p><h4>Example:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9f748d872e722584a435eb4b538f021/href">https://medium.com/media/c9f748d872e722584a435eb4b538f021/href</a></iframe><p>Consumer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f82063e99969c2009b568a72f54f0beb/href">https://medium.com/media/f82063e99969c2009b568a72f54f0beb/href</a></iframe><p>Output:</p><pre>Processing of: a<br>aa<br>Processing of: b<br>…</pre><p>As we can see, the result of the processing of the first element — “<strong>aa</strong>” is available for the user before the processing of the next element started, but still, the computation is the stream’s producer responsibility. In other words, the consumer decides <strong>when and if</strong> the computation should be performed, but the producer is still responsible for <strong>how</strong> to perform the computation.</p><p>You may think that’s easy and you don’t need a stream. Sure, you’re right, let’s take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0016df9255846e8d1d53c448bda58236/href">https://medium.com/media/0016df9255846e8d1d53c448bda58236/href</a></iframe><p>And the consumer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67bb4ee11eb1f15155f48cdfb0258bd0/href">https://medium.com/media/67bb4ee11eb1f15155f48cdfb0258bd0/href</a></iframe><p>We’ve achieved the same result but for the price of encapsulation — expensiveStringDoubler has to become public and what’s even worse, now the consumer is responsible for calling it.</p><p>But wait, we can do better:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82297bc650ff3d3a647397e8e70bef0f/href">https://medium.com/media/82297bc650ff3d3a647397e8e70bef0f/href</a></iframe><p>And the consumer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27b348eab40fcddd3d633346e7845a4f/href">https://medium.com/media/27b348eab40fcddd3d633346e7845a4f/href</a></iframe><p>Again the same effect, but actually we have reinvented the wheel, our implementation mimics stream’s ancestor — Iterator and we’ve lost the advantage of stream’s API.</p><h3>Avoid premature computation</h3><p>Assume again we have a time-consuming operation to be performed on each stream element. There are situations when a consumer of the API can’t say in advance how much data is required. For example:</p><ul><li>user canceled data loading</li><li>an error occurred during data processing and there is no need to process the rest of the data</li><li>consumer reads data until a condition is met e.g. first positive value</li></ul><p>Thanks to the laziness of streams some computations can be avoided in such situations.</p><h4>Example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c646ea01fcf7e2e9226b7cf0857a05/href">https://medium.com/media/78c646ea01fcf7e2e9226b7cf0857a05/href</a></iframe><p>Consumer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784f0a791015aa5be7442a6e4ddecd7a/href">https://medium.com/media/784f0a791015aa5be7442a6e4ddecd7a/href</a></iframe><p>In the example, the consumer reads the data until the value is greater than 0.4. The producer is not aware of such logic of the consumer, but it computes only as many items as necessary. The logic (e.g. the condition) can be changed independently at the consumer side.</p><h3>API easy to use</h3><p>There is one more reason to use streams instead of custom API design. Streams are part of the standard library and well known for many developers. Using streams in our API makes it easier for other developers to use the API.</p><h3>Additional considerations</h3><h4>Error handling</h4><p>Traditional error handling doesn’t work with Streams. Because actual processing is postponed until required, the exception can’t be thrown when the stream is constructed. Basically, we have two options:</p><ul><li>throw a RuntimeException — the exception will be thrown by the termination method (e.g. forEach)</li><li>wrap the element into an object representing the current state of the element being processed e.g. specialized Try class from Vavr library (details in the<a href="https://blog.softwaremill.com/exceptions-no-just-try-them-off-497984eb470d"> blog</a>)</li></ul><h4>Resource management</h4><p>Sometimes we have to use a resource to provide stream data (e.g. session in an external service) and we want to release it when the stream processing is finished. Fortunately, stream implements Autoclosable interface and we can use a stream in try-with-resources statements making resource management very easy. All we have to do is to register a hook in the stream with the onClose method. The hook will be automatically called when the stream is closed.</p><h4>Example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f3d31d7cb4a113d13f67f18ad6665f/href">https://medium.com/media/c5f3d31d7cb4a113d13f67f18ad6665f/href</a></iframe><p>Consumer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82691ed9bf1e4277c5164f6dbba6fe7f/href">https://medium.com/media/82691ed9bf1e4277c5164f6dbba6fe7f/href</a></iframe><p>Output:</p><pre>0.2264004802916616<br>0.32777949557515484</pre><pre>Releasing resources…</pre><pre>Exception in thread “main” java.lang.RuntimeException: Data processing exception</pre><p>In the example, when data processing exception occurs the stream is automatically closed by try-with-resources statement and the registered handler is called. In the example output, we can see Releasing resources… message printed by the handler.</p><h3>Wrap up</h3><ol><li>Streams are not collections.</li><li>Streams can help us solve issues like:<br>* Processing a large volume of data<br>* Fast access to (incomplete) data<br>* Avoid premature computation</li><li>It’s not so hard to build a stream.</li><li>We have to take care of error handling.</li><li>Resource management is supported.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c30e7ebc5407" width="1" height="1" alt=""><hr><p><a href="https://blog.softwaremill.com/why-when-and-how-to-return-stream-from-your-java-api-instead-of-a-collection-c30e7ebc5407">Why, when and how to return Stream from your Java API instead of a collection</a> was originally published in <a href="https://blog.softwaremill.com/">SoftwareMill Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>