<?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 Davide Cerbo on Medium]]></title>
        <description><![CDATA[Stories by Davide Cerbo on Medium]]></description>
        <link>https://medium.com/@davidecerbo?source=rss-96739cbc436------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oVOLYeoOrAeCeedN.jpg</url>
            <title>Stories by Davide Cerbo on Medium</title>
            <link>https://medium.com/@davidecerbo?source=rss-96739cbc436------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:30:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidecerbo/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[Streaming Valid JSON from AI with SSE (Without Breaking Your Frontend)]]></title>
            <link>https://davidecerbo.medium.com/streaming-valid-json-from-ai-with-sse-without-breaking-your-frontend-60f97c81e64f?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f97c81e64f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ai-programming]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 16:43:05 GMT</pubDate>
            <atom:updated>2026-04-22T16:43:05.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7yVnX8pRzbiXIsdxev2WQ.png" /></figure><p>When you start streaming AI responses in real time, everything feels smooth… until JSON enters the picture.</p><p>If you’re using <strong>Server-Sent Events (SSE)</strong> with Java and Spring, and your AI returns structured output, you’ll hit this problem almost immediately:</p><blockquote><em>The model streams partial text, but JSON must always be valid.</em></blockquote><p>And that’s where things break.</p><p>The article uses Java and Spring AI, but of course you can adapt to your favourite language and library.</p><h3>The Problem Nobody Mentions</h3><p>Let’s say your AI is generating this:</p><pre>[<br>  { &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30 },<br>  { &quot;name&quot;: &quot;Anna&quot;, &quot;age&quot;: 25 }<br>]</pre><p>In streaming mode, what you actually receive looks more like:</p><pre>[<br>  { &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 3</pre><p>Or:</p><pre>[<br>  { &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30 },<br>  { &quot;name&quot;: &quot;Anna&quot;,</pre><p>These are <strong>invalid JSON fragments</strong>.</p><p>If you forward them directly to the frontend:</p><ul><li>JSON.parse() will fail</li><li>your UI may crash</li><li>or worse, behave inconsistently</li></ul><h3>A Different Approach: Stream State, Not Chunks</h3><p>Instead of streaming raw tokens, we change perspective:</p><blockquote><em>Every event must contain a valid JSON.</em></blockquote><p>So the strategy becomes:</p><ol><li>Accumulate the response progressively</li><li>Fix the JSON at every step</li><li>Send the <strong>entire valid JSON snapshot</strong></li></ol><p>Yes, this means:</p><p>👉 Each SSE event contains the full JSON, not just a delta</p><p>It may sound inefficient — but it works incredibly well.</p><h3>The Key Piece: A JSON Fixer</h3><p>To make this possible, we introduce a small but powerful component:</p><pre>public class JsonFixer {<br>    public String fix(String response) {<br>        String json = findJson(response);<br>        if (json == null || json.isEmpty()) {<br>            return &quot;[]&quot;;<br>        }<br>        json = json.trim().replaceAll(&quot;\n&quot;, &quot;&quot;);<br>        // Stack + state machine logic to repair JSON<br>        // (handles strings, truncation, commas, brackets, etc.)<br>        return result.toString();<br>    }<br>}</pre><p>You can find the full code on <a href="https://gist.github.com/jesty/23461fc144505be24658742787fa5882">https://gist.github.com/jesty/23461fc144505be24658742787fa5882</a></p><p>What it does:</p><ul><li>closes open { and [</li><li>completes broken strings</li><li>removes trailing commas</li><li>fixes incomplete key/value pairs</li></ul><p>Example:</p><pre>[{ &quot;name&quot;: &quot;Anna&quot;,</pre><p>Becomes:</p><pre>[{ &quot;name&quot;: &quot;Anna&quot;, &quot;&quot; : &quot;&quot; }]</pre><p>Not perfect — but always valid.</p><p>And that’s the only guarantee we need.</p><h3>The Spring AI Streaming Endpoint</h3><p>Here’s how you wire everything together using Spring AI and SSE:</p><pre>@GetMapping(value = &quot;/stream&quot;, produces = MediaType.TEXT_EVENT_STREAM_VALUE)<br>public Flux&lt;ServerSentEvent&lt;String&gt;&gt; streamGet() throws IOException {<br>    String promptText = &quot;Your prompt here&quot;;<br>    StringBuilder localCollector = new StringBuilder();<br>    JsonFixer fixer = new JsonFixer();<br>    return chatClient<br>            .prompt()<br>            .system(&quot;Bla bla bla&quot;)<br>            .user(u -&gt; u.text(promptText))<br>            .stream()<br>            .chatResponse()<br>            .filter(response -&gt; response.getResult() != null)<br>            .map(response -&gt; response.getResult().getOutput().getText())<br>            .filter(text -&gt; text != null &amp;&amp; !text.isEmpty())<br>            // Accumulate partial chunks<br>            .doOnNext(localCollector::append)<br>            // Rebuild full response so far<br>            .map(s -&gt; localCollector.toString())<br>            .filter(s -&gt; !s.isEmpty())<br>            // Fix JSON at every step<br>            .map(fixer::fix)<br>            // Emit full valid JSON via SSE<br>            .map(text -&gt; ServerSentEvent.&lt;String&gt;builder()<br>                    .data(text)<br>                    .build())<br>            // Avoid sending identical snapshots<br>            .distinctUntilChanged();<br>}</pre><h3>What’s Really Happening</h3><p>The flow is simple but powerful:</p><ul><li>The AI streams partial text</li><li>We accumulate everything</li><li>We repair the JSON continuously</li><li>We emit only valid snapshots</li></ul><p>So instead of:</p><pre>chunk → chunk → chunk</pre><p>We send:</p><pre>valid JSON → bigger valid JSON → final JSON</pre><h3>Why This Works So Well</h3><h3>Frontend becomes trivial</h3><pre>const eventSource = new EventSource(&quot;/stream&quot;);<br>eventSource.onmessage = (event) =&gt; {<br>  const data = JSON.parse(event.data);<br>  render(data);<br>};</pre><p>No buffering. No retries. No hacks.</p><h3>It’s resilient to model behavior</h3><p>LLMs are not guaranteed to:</p><ul><li>close brackets</li><li>finish strings</li><li>respect JSON boundaries</li></ul><p>This approach doesn’t care.</p><h3>Trade-offs (and Why They’re Worth It)</h3><h3>Cons</h3><ul><li>More data sent (full JSON each time)</li><li>Extra CPU for fixing</li></ul><h3>Pros</h3><ul><li>Zero parsing errors</li><li>Deterministic UI updates</li><li>Simpler frontend</li><li>Works with any framework</li></ul><p>In most real-world apps, this is an easy win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f97c81e64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where is my Datadog APM Trace?]]></title>
            <link>https://davidecerbo.medium.com/where-is-my-datadog-apm-trace-12ef99475cbf?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ef99475cbf</guid>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[apm]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 13:35:24 GMT</pubDate>
            <atom:updated>2026-04-21T13:35:24.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKUDd6UccS0xxCzBWBelXw.png" /></figure><p>It started with a simple observation: some requests I was sending through Postman never showed up in Datadog traces.</p><p>At first, I assumed something was broken in the instrumentation. Maybe the service wasn’t properly configured, or the traces weren’t reaching the agent.</p><p>But the deeper I looked, the clearer it became: nothing was broken. Everything was working exactly as designed.</p><p>The problem was <strong>sampling</strong>.</p><h3>The Invisible Filter Between Your Requests and Datadog</h3><p>What I had overlooked is that Datadog does not store every trace it receives.</p><p>Instead, it samples aggressively:</p><ul><li>Services can send ~100 traces/sec to the Agent</li><li>The Agent typically keeps ~10 traces/sec</li></ul><p>In a Kubernetes environment, this gets amplified in a subtle but dangerous way. You don’t have one workload — you have hundreds of pods competing for a very limited trace budget.</p><p>In my case, the math was brutal:</p><ul><li>19 nodes × ~10 traces/sec ≈ 190 traces/sec retained</li><li>~927 pods generating traffic</li></ul><p>So in practice:</p><blockquote><em>Only about </em><strong><em>20% of requests were actually making it into Datadog</em></strong></blockquote><p>And it wasn’t random either.</p><h3>The Silent Bias of Adaptive Sampling</h3><p>Datadog doesn’t just sample uniformly. It applies <strong>adaptive sampling</strong>, which favors less frequent operations and penalizes noisy ones.</p><p>That means:</p><ul><li>/health endpoints get down-prioritized because they are extremely frequent</li><li>GraphQL and search endpoints often get heavily thinned out</li><li>The more an endpoint is called, the less likely you are to see it</li></ul><p>This creates an uncomfortable illusion:</p><blockquote><em>The endpoints you think you are observing are often the least visible ones in practice.</em></blockquote><h3>The First Wrong Idea: Just Remove /health</h3><p>A natural reaction is: “Let’s just exclude /health entirely from tracing.”</p><p>It works — on paper.</p><p>But in reality, it creates a blind spot.</p><p>Health endpoints are boring until they aren’t. When they fail, they often signal the first sign of real production issues. Removing them entirely means losing visibility exactly when you need it most.</p><p>So instead of removing noise, I needed a way to <strong>preserve failure signals without flooding the system</strong>.</p><h3>A Better Approach: Keep the Noise, Elevate the Failures</h3><p>The solution I ended up with was more surgical: keep /health traces, but <strong>force priority when something goes wrong</strong>.</p><p>Instead of treating all requests equally, I started explicitly upgrading failed ones.</p><p>Here’s the filter I used:</p><pre>import atadog.trace.api.interceptor.MutableSpan;<br>import datadog.trace.api.GlobalTracer;<br>import javax.servlet.*;<br>import javax.servlet.http.HttpServletResponse;<br>import java.io.IOException;<br>public class DatadogHealthFilter implements Filter {<br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)<br>            throws IOException, ServletException {<br>        chain.doFilter(request, response);<br>        if (response instanceof HttpServletResponse res) {<br>            int status = res.getStatus();<br>            if (status &gt;= 500) {<br>                MutableSpan span = (MutableSpan) GlobalTracer.get().activeSpan();<br>                if (span != null) {<br>                    span.setSamplingPriority(1); // force keep<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>@Bean<br>public FilterRegistrationBean&lt;DatadogHealthFilter&gt; healthFilter() {<br>    FilterRegistrationBean&lt;DatadogHealthFilter&gt; reg = new FilterRegistrationBean&lt;&gt;();<br>    reg.setFilter(new DatadogHealthFilter());<br>    reg.addUrlPatterns(&quot;/actuator/health&quot;);<br>    return reg;<br>}</pre><h3>What This Actually Changed</h3><p>This small adjustment shifted the model:</p><ul><li>Normal health checks → still cheap, still sampled</li><li>Failed health checks → always retained</li><li>No explosion in trace volume</li><li>No loss of critical failure visibility</li></ul><p>In other words, I stopped treating observability as binary (“trace or don’t trace”) and started treating it as <strong>prioritized signal engineering</strong>.</p><h3>Final Insight</h3><p>The real lesson wasn’t about Datadog configuration.</p><p>It was this:</p><blockquote><em>In distributed systems, observability is not about collecting everything — it’s about deciding what deserves to survive the sampling filter.</em></blockquote><p>Once you accept that, the goal changes:<br> not “why am I missing traces?”, but “what signals are important enough to never lose?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ef99475cbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Feature Flags Best Practices with Java examples]]></title>
            <link>https://davidecerbo.medium.com/9-feature-flags-best-practices-with-java-examples-e43b623dda08?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43b623dda08</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[trunk-based-development]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 23:12:27 GMT</pubDate>
            <atom:updated>2024-11-27T23:12:27.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCuBdOwKCF6ESQPV" /><figcaption>Photo by <a href="https://www.pexels.com/it-it/@alenakroon/">Alena Sharkova</a></figcaption></figure><p>During the last year we introduced <strong>continuous deployment</strong> in our project.</p><p>This was really a huge improvement, now we don’t have to wait anymore a release, I mean months, to ship a new feature or a bug fixing to a customer, we can ship in days.</p><p>One of the biggest thing we had to change in our way of working it was moving from a feature-based to a trunk-based development approach.</p><p><strong>Merging often means failing first, that it is good, but also failing often that it’s now good</strong>, so one thing that we should always keep in mind is that we have to be <strong>tremendously fast in going in production</strong>. If not, we are not read for trunk-based development and feature flags :).</p><h3>1. Don’t merge a new feature without a feature flag</h3><p>No excuse, we cannot take this risk.</p><h3>2. Always have a rollback strategy</h3><p>What happens if we have to disable the feature flag after we enabled it? We should always have a rollback strategy in mind, or at least to document steps to restore the system.</p><h3>3. Don’t spam your feature flag around the code</h3><p>Please, use your flag in as few places as possible. Having a feature flag is an often underrated cost in terms of time and bugs. We should try to design our code in order to have a reference to the feature flag in only one place, so when we are going to remove it we have just to delete entire piece of code like methods, classes, functions, not fractions.</p><h3>4. <strong>Abstraction, always abstraction!</strong></h3><p>We should abstract always how the code should behave depending on a feature flag value from the application logic. This will keep our code clean and maintainable and we can easily change the behaviour without compromising the existing code. This will simplify also the feature flag removal.</p><h3><strong>5</strong>. Create small PR and as soon as possible</h3><p>Feature Flag allows you to merge also a not finished features if you are not breaking nothing. Customers will never see it, but:</p><ul><li>team mates can start giving meaningfull feedbacks</li><li>PR review will be simpler and better</li><li>errors and regressions will be easily recognizable</li></ul><h3>6. Clean Up Obsolete Flags</h3><p>At the beginning of each release we should plan the removal of the feature flags enabled during the previous period.</p><h3>7. No dependencies between flags</h3><p>Avoid situations where one flag needs to be enabled in order for another flag to work. This can quickly become complex and difficult to manage, so it is important to keep things simple and independent.</p><h3>8. Choose the right name</h3><p>For each feature flag we have to provide a key and a name. The rule that we have to follow should be:</p><h3>9. <strong>Don’t use feature flags for similar things</strong></h3><p>Even if we thing that we can put similar things behind the same feature flag, basically reusing it, it’s not sure that we want to enable everything at the same time, or that we don’t want to affect all the users in the same way.</p><h3>Backend examples</h3><p>Examples below are mostly in Java and Spring, but you can easily adapt to your favourite language and framework.</p><h3>Add a different behaviour in a method</h3><p>We should extract a method and create a new one.</p><p>From:</p><pre>private MyClass getMyInstance() {<br>            //doing something<br>    }</pre><p>To:</p><pre>private MyInterface getMyInterfaceImplementation() {<br>    if (launchDarklyClient.boolVariation(&quot;FLAG_NAME&quot;)) {<br>        return buildNewImplementations();<br>    } else {<br>        return buildOriginalImplementation();<br>    }<br>}<br><br>private MyInterface buildNewImplementations() {<br>  //doing something different<br>}<br><br>private MyInterface buildOriginalImplementation() {<br>  //doing something<br>}</pre><h3>Huge behavioural change</h3><p>We have to create an interface or abstract class and create two implementations.</p><p>The PR for introducing the Interface and relative refactoring must be done in a separate PR in order to keep the main PR simple to review, and the second PR focused on the new feature.</p><p>From:</p><pre>public class SendEmailWithAttachment {<br>  //This class send an email with an attachment using Java API<br>}</pre><pre>@Configuration<br>public class EmailConfiguration {<br>  @Bean<br>  public SendEmailWithAttachment sendEmailWithAttachment() {<br>    return new SendEmailWithAttachment(...);<br>  }<br>}</pre><p>To:</p><pre>public interface SendEmailWithAttachment {<br>  //This class send an email with an attachment using Java API<br>}</pre><pre>public interface JavaAPiSendEmailWithAttachment implements SendEmailWithAttachment {<br>  //This class send an email with an attachment using Java API<br>}</pre><pre>public interface MailChimpSendEmailWithAttachment implements SendEmailWithAttachment {<br>  //This class send an email with an attachment using MailChimp API<br>}</pre><pre>@Configuration<br>public class EmailConfiguration {<br>  @Bean<br>  public SendEmailWithAttachment javaApiSendEmailWithAttachment() {<br>    if (launchDarklyClient.boolVariation(&quot;FLAG_NAME&quot;)) {<br>      return new MailChimpSendEmailWithAttachment(...);<br>    } else {<br>      return new JavaAPiSendEmailWithAttachment(...);<br>    }<br>  }<br>}</pre><h3>Update or introduce a new REST API</h3><p>If we are working on a REST API and you don’t want to show to the end user until the Feature Flag it’s enabled you can use the io.swagger.v3.oas.annotations.Hidden annotation. This applies also when you are adding a new parameter, or a single parameter in an existing Controller class.</p><p>This is not going to be visible automatically, so you have to remove with another PR the annotation once the feature flag has been enabled.</p><p>If you are working on a new controller class you could do also a trick in order to make che REST API visible only when the Feature flag it’s enabled:</p><pre>@ComponentScan(excludeFilters = @Filter(NewFeatureRestController.class))<br>public class DemoApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(DemoApplication.class, args);<br>    }<br>}</pre><pre>@Configuration<br>public class NewFeatureConfiguration {<br>    @Bean<br>    public NewFeatureRestController newFeatureRestController () {<br>      if (launchDarklyClient.boolVariation(&quot;FLAG_NAME&quot;)) {<br>        return new NewFeatureRestController(featureXService());<br>      } else {<br>        return null;<br>      }<br>    }<br>}</pre><h3>Change a database column</h3><p>In order to don’t do breaking changes we shouldn’t never overwrite a column value or perform an hard type change (e.g. String to Number) on a database field. If we have to perform this kind of operation we should always create a new column leaving the old one for a while.</p><p>For instance if we want to change the field code from Integer to String. We have to:</p><ol><li>create the new column codeStr of type String</li><li>using a db change management library (e.g. Liquibase) we should define the migration from Integer to String for old values</li><li>update the code in order to use both fields for a while. Here we have to do the first PR.</li><li>after enabling the Feature Flag we can drop the old column. Here we have to do a second PR.</li></ol><p>We cannot do everything all together because we can cause temporary errors, for instance if we have more instances of the same service, Kubernetes will keep always one alive, so it means that the old column could be used while we are performing the upgrade.</p><h3>References</h3><ul><li><a href="https://posthog.com/docs/feature-flags/best-practices">https://posthog.com/docs/feature-flags/best-practices</a></li><li><a href="https://docs.getunleash.io/topics/feature-flags/feature-flag-best-practices">https://docs.getunleash.io/topics/feature-flags/feature-flag-best-practices</a></li><li><a href="https://launchdarkly.com/blog/the-five-stages-of-feature-flag-adoption/">https://launchdarkly.com/blog/the-five-stages-of-feature-flag-adoption/</a></li><li><a href="https://launchdarkly.com/blog/feature-flag-mistakes/">https://launchdarkly.com/blog/feature-flag-mistakes/</a></li><li><a href="https://martinfowler.com/articles/feature-toggles.html">https://martinfowler.com/articles/feature-toggles.html</a></li><li>A good talk about continuous deployment to watch <a href="https://www.youtube.com/watch?v=ylVogFl36zM">https://www.youtube.com/watch?v=ylVogFl36zM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43b623dda08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Spring Native and $ave mon€y]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/javarevisited/use-spring-native-and-save-money-655ffba0b616?source=rss-96739cbc436------2"><img src="https://cdn-images-1.medium.com/max/1060/1*w3csbclq5ZT9kQ_e2Y4RmA.png" width="1060"></a></p><p class="medium-feed-snippet">Spring native is the way to compile Spring applications to native images with GraalVM without changing anything (or at least some stuff)&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/javarevisited/use-spring-native-and-save-money-655ffba0b616?source=rss-96739cbc436------2">Continue reading on Javarevisited »</a></p></div>]]></description>
            <link>https://medium.com/javarevisited/use-spring-native-and-save-money-655ffba0b616?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/655ffba0b616</guid>
            <category><![CDATA[spring-native]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 21:57:06 GMT</pubDate>
            <atom:updated>2021-10-01T15:56:59.816Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Spring Native first fight!]]></title>
            <link>https://davidecerbo.medium.com/spring-native-first-fight-6e72bf7c3e03?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e72bf7c3e03</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[spring-native]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 15:25:44 GMT</pubDate>
            <atom:updated>2021-03-24T16:17:59.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Waiting for a more complete article about my (short) experience with <a href="https://github.com/spring-projects-experimental/spring-native">Spring Native</a>, I’m proud to share a configuration used to configure an application that uses <a href="https://www.elastic.co/">Elasticsearch</a>, <a href="https://camel.apache.org/">Apache Camel</a>, and <a href="https://activemq.apache.org/">Apache ActiveMQ</a>.</p><p>I got help reading (and copying :D) some code in the <a href="https://github.com/apache/camel-quarkus">Apache Camel extensions for Quarkus</a> and in the <a href="https://github.com/spring-projects-experimental/spring-native/blob/master/spring-native-configuration/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesHints.java">ElasticsearchRepositoriesHint</a> provided by Spring doesn’t work for me because I’m using Elasticsearch without Spring Data.</p><p>Before finish I have to say thanks to my friend <a href="https://twitter.com/robfrankie">Roberto</a> to help me with that migration.</p><p>And now, as Linus Torvald said: talk is cheap, show me the code!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a1c9d4fa7932fee53034ce7fc0f54b/href">https://medium.com/media/74a1c9d4fa7932fee53034ce7fc0f54b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e72bf7c3e03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How difficult can it ever be to build a list of objects in Java and Kotlin using the builder…]]></title>
            <link>https://davidecerbo.medium.com/how-difficult-can-it-ever-be-to-build-a-list-of-objects-in-java-and-kotlin-using-the-builder-fb0d0a8a5ca6?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0d0a8a5ca6</guid>
            <category><![CDATA[data-class]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Wed, 27 May 2020 22:57:04 GMT</pubDate>
            <atom:updated>2020-05-27T23:04:20.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>How difficult can it ever be to build a list of objects in Java and Kotlin using the builder pattern?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UsZVVYFIzPz_8SIZsk4mw.jpeg" /></figure><p>Hello everyone! Some days ago I had to build a list of objects and I would like to use the Builder pattern.</p><blockquote>You don’t bother about Java? Skip to <a href="#5693">Kotlin</a>!</blockquote><p>In this example, I will image that I will build an automobile manufacturers list, so I will have a classic <strong>Manufacturer</strong> builder that I can use like:</p><pre>Manufacturer manufacturer = new ManufacturerBuilder()<br>   .withName(&quot;Fiat Automobiles S.p.A&quot;)<br>   .withNationality(&quot;Italian&quot;)<br>   .withContinent(&quot;Europe&quot;)<br>   .withFoundationYear(1899)<br>   .build();</pre><p>I have a builder and obviously my <strong>Manufacturer object is immutable</strong>!</p><p>I need a list of manufacturers and I wouldn’t write verbose code like:</p><pre>List&lt;Manufacturer&gt; euroManufacturers = new LinkedList&lt;&gt;();</pre><pre>manufacturers.<strong>add</strong>(new ManufacturerBuilder()<br>   .<strong>withName</strong>(&quot;Fiat Automobiles S.p.A&quot;)<br>   .<strong>withNationality</strong>(&quot;Italian&quot;)<br>   .<strong>withContinent</strong>(&quot;Europe&quot;)<br>   .<strong>withFoundationYear</strong>(1899)<br>   .<strong>build</strong>());</pre><pre>manufacturers.<strong>add</strong>(new ManufacturerBuilder()<br>   .<strong>withName</strong>(&quot;Peugeout&quot;)<br>   .<strong>withNationality</strong>(&quot;French&quot;)<br>   .<strong>withContinent</strong>(&quot;Europe&quot;)<br>   .<strong>withFoundationYear</strong>(1899)<br>   .<strong>build</strong>());</pre><p>After some refactoring and tests, I finally decide to have a ManufacturerListBuilder with an <strong>add</strong> method that accepts in input a <strong>Function&lt;UserFilterBuilder, UserFilterBuilder&gt;</strong>, so I can provide a builder every time I need to add an element using my builder, let’s look to the usage:</p><pre>List&lt;Manufacturer&gt; euroManufacturers = new ManufacturerListBuilder()<br>           .<strong>withContinent</strong>(&quot;Europe&quot;)<br>           .<strong>add</strong>(builder -&gt; builder<br>                  .<strong>withName</strong>(&quot;Fiat Automobiles S.p.A&quot;)<br>                  .<strong>withNationality</strong>(&quot;Italian&quot;)<br>                  .<strong>withFoundationYear</strong>(1899))<br>           .<strong>add</strong>(builder -&gt; builder<br>                  .<strong>withName</strong>(&quot;Peugeout&quot;)<br>                  .<strong>withNationality</strong>(&quot;French&quot;)<br>                  .<strong>withFoundationYear</strong>(1810))       <br>           .<strong>getManufacturers</strong>();</pre><p>As you can see the code looks more compact and the list build responsibility is delegated to a specific class that I can easily reuse everywhere.</p><p>Moreover, I can extract a method to set the common values for the builders, so I don’t have to set the continent for each manufacturer.</p><p>How I implement the ManufacturerListBuilder? It was very simple, the core of the solution is the <strong>add</strong> method:</p><pre>class ManufacturerListBuilder {<br>    <br>    private String continent;<br>    private final List&lt;Manufacturer&gt; manufacturers = new LinkedList&lt;&gt;();<br><br>    public ManufacturerListBuilder <strong>withContinent</strong>(String continent) {<br>        this.continent = continent;<br>        return this;<br>    }<br><br>    ManufacturerListBuilder <strong>add</strong>(Function&lt;ManufacturerBuilder, ManufacturerBuilder&gt; builderFunction) {<br>        <br>        ManufacturerBuilder builder = ManufacturerBuilder<br>           .apply(new ManufacturerBuilder()<br>                        .withContinent(continent))<br>           .build();<br><br>        this.manufacturers.<strong>add</strong>(builder);<br>        return this;<br>    }<br><br>    public Collection&lt;UserFilter&gt; <strong>getManufacturers</strong>() {<br>        return this.manufacturers;<br>    }<br>}</pre><p>But there is a problem, the <strong>withContinent</strong> method works only if invoked before adding elements to the list, or wait, <strong>this is a bug or a feature?</strong> This permits me to use multiple continents in the same builder:</p><pre>List&lt;Manufacturer&gt; manufacturers = new ManufacturerListBuilder()<br>           .<strong>withinContinent</strong>(&quot;Europe&quot;)<br>           .<strong>add</strong>(builder -&gt; builder<br>                  .<strong>withName</strong>(&quot;Fiat Automobiles S.p.A&quot;)<br>                  .<strong>withNationality</strong>(&quot;Italian&quot;)<br>                  .<strong>withFoundationYear</strong>(1899))<br>           .<strong>add</strong>(builder -&gt; builder<br>                  .<strong>withName</strong>(&quot;Peugeout&quot;)<br>                  .<strong>withNationality</strong>(&quot;French&quot;)<br>                  .<strong>withFoundationYear</strong>(1810))<br>           .<strong>withinContinent</strong>(&quot;America&quot;)<br>           .<strong>add</strong>(builder -&gt; builder<br>                  .<strong>withName</strong>(&quot;Chevrolet&quot;)<br>                  .<strong>withNationality</strong>(&quot;USA&quot;)<br>                  .<strong>withFoundationYear</strong>(1911))             <br>           .<strong>getManufacturers</strong>();</pre><p>So, to better dress the bug to a beautiful feature I renamed the method to <strong>withinContinent</strong>.</p><p>But how this code will looks in Kotlin? Without any refactoring we can use the builder as below:</p><pre>val manufacturers = ManufacturerListBuilder()<br>           .<strong>withinContinent</strong>(&quot;Europe&quot;)<br>           .<strong>add </strong>{<br>                  it.<strong>withName</strong>(&quot;Fiat Automobiles S.p.A&quot;)<br>                    .<strong>withNationality</strong>(&quot;Italian&quot;)<br>                    .<strong>withFoundationYear</strong>(1899)<br>                 }<br>           .<strong>add </strong>{<br>                  it.<strong>withName</strong>(&quot;Peugeout&quot;)<br>                    .<strong>withNationality</strong>(&quot;French&quot;)<br>                    .<strong>withFoundationYear</strong>(1810)<br>                }            <br>           .<strong>getManufacturers</strong>();</pre><p>But <strong>in Kotlin we don’t need builders</strong>, because we can rely on <strong>named parameters</strong>.</p><p>So we can delete everything and write:</p><pre>data class <strong>Manufacturer</strong>(val name: String,<br>                        val nationality: String,<br>                        val continent: String,<br>                        val foundationYear: Int)<br><br><br>fun example() {<br>    val manufacterers = <em>listOf</em>(<br>            <strong>Manufacturer</strong>(name = &quot;Fiat&quot;, nationality = &quot;Italian&quot;,<br>                    continent = &quot;Europe&quot;, foundationYear = 1891),<br>            <strong>Manufacturer</strong>(name = &quot;Peugeout&quot;, nationality = &quot;France&quot;,<br>                    continent = &quot;Europe&quot;, foundationYear = 1810),<br>            <strong>Manufacturer</strong>(name = &quot;Chevrolet&quot;, nationality = &quot;USA&quot;,<br>                    continent = &quot;America&quot;, foundationYear = 1911)<br>    )<br>}</pre><p>But we miss a feature, we cannot build Manufacturer instances without repeating the continent. We can solve this using <strong>Sealed classes</strong>, <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">that are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type</a>.</p><p>So we transform the <strong>Manufacturer </strong>from a <strong>data</strong> to a <strong>sealed</strong> class and we define the class hierarchies, one for each continent:</p><pre>sealed class <strong>Manufacturer</strong>(open val name: String,<br>                          open val nationality: String,<br>                          val continent: String,<br>                          open val foundationYear: Int)<br><br>data class <strong>EuropeanManufacturer</strong>(override val name: String,<br>                                override val nationality: String,<br>                                override val foundationYear: Int)<br>    : <strong>Manufacturer</strong>(name, nationality, &quot;America&quot;, foundationYear)<br><br>data class <strong>AmericanManufacturer</strong>(override val name: String,<br>                                override val nationality: String,<br>                                override val foundationYear: Int)<br>    : <strong>Manufacturer</strong>(name, nationality, &quot;Europe&quot;, foundationYear)<br><br><br>fun <strong>example</strong>() {<br>    <em>listOf</em>(<br>        <strong>EuropeanManufacturer</strong>(<br>                name = &quot;Fiat&quot;,<br>                nationality = &quot;Italian&quot;,<br>                foundationYear = 1891),<br>        <strong>EuropeanManufacturer</strong>(<br>                name = &quot;Peugeout&quot;,<br>                nationality = &quot;France&quot;, foundationYear = 1810),<br>        <strong>AmericanManufacturer</strong>(<br>                name = &quot;Chevrolet&quot;,<br>                nationality = &quot;USA&quot;,<br>                foundationYear = 1911)<br>    )<br>}</pre><p>I’m still not happy, I don’t like to repeat the parameters in the constructor, but I can avoid them <strong>defining all the constructor parameters as abstract fields except the field that I must set as default</strong>:</p><pre>sealed class <strong>Manufacturer</strong>(val continent: String){<br>    abstract val name: String<br>    abstract val nationality: String<br>    abstract val foundationYear: Int<br>}<br><br>data class <strong>EuropeanManufacturer</strong>(val name: String,<br>                                val nationality: String,<br>                                val foundationYear: Int)<br>    : <strong>Manufacterer</strong>(&quot;America&quot;)<br><br>data class <strong>AmericanManufacturer</strong>(val name: String,<br>                                val nationality: String,<br>                                val foundationYear: Int)<br>    : <strong>Manufacterer</strong>(&quot;Europe&quot;)</pre><p>Now the code looks pretty good!</p><p>What we are doing? We are doing <strong>Object-Oriented Programming, </strong>we are using <strong>polymorphism.</strong></p><p>Defining a class that refers to a continent enable us of using pattern matching, so we can do some kind of magic like filtering all manufacturer by type:</p><pre>   val europeansManufacturer = <br>              manufacturers.<strong>filterIsInstance</strong>&lt;EuropeanManufacturer&gt;()</pre><pre>    val americansManufacturer = <br>              manufacturers.<strong>filterIsInstance</strong>&lt;AmericanManufacturer&gt;()</pre><p>Describing it using <strong>pattern matching</strong>:</p><pre>fun <strong>example</strong>() {<br>    manufacturers.<em>forEach </em><strong>{<br>        </strong><em>println</em>(<em>describe</em>(<strong>it</strong>))<br>    <strong>}<br></strong>}<br><br>fun <strong>describe</strong>(m: Manufacturer) = <strong>when</strong> (m) {<br>    <strong>is</strong> EuropeanManufacturer -&gt; &quot;${m.name} is an European.&quot;<br>    <strong>is</strong> AmericanManufacturer -&gt; &quot;${m.name} is an American.&quot;<br>}</pre><p>And many others magics ;)</p><h3>Further reading</h3><p>In the past, I wrote two articles like that, unfortunately, they are in Italian, but there is a lot of code, so you can understand them even just by reading the code ;)</p><ul><li><a href="https://medium.com/@davidecerbo/can-kotlin-do-it-better-966e9d6ecbb1">Can Kotlin do it better?</a></li><li><a href="https://medium.com/@davidecerbo/kotlin-vs-java-maps-6dcb6f4f21cd">Kotlin vs. Java: Maps</a></li><li><a href="https://medium.com/@davidecerbo/kotlin-vs-java-fibonacci-d76c5b282ea">Kotlin vs. Java: Fibonacci</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0d0a8a5ca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Kotlin do it better?]]></title>
            <link>https://davidecerbo.medium.com/can-kotlin-do-it-better-966e9d6ecbb1?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/966e9d6ecbb1</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 19:26:07 GMT</pubDate>
            <atom:updated>2020-05-27T23:05:09.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*8maKIgAvyRdRS0rYu6xbQQ.png" /></figure><p>In this post I will do a simple refactoring of a real small piece of code that I found in a legacy code base and after I will translate the example to Java to Kotlin. Why? Only in order to demonstrate why Kotlin can be useful for writing more maintainable code and <strong>not only a fashionable language for old Java developer, like me</strong> :)</p><p>Every day we face simple problems like splitting a list into two new lists.</p><pre>public void myMethod(A source, B destination) {<br>    List&lt;Credentials&gt; list = source.getCredentials();<br>    Set&lt;String&gt; users = new HashSet&lt;&gt;();<br>    Set&lt;String&gt; groups = new HashSet&lt;&gt;();</pre><pre>    for (Credentials item : list) {<br>       if (item.isActive()) {<br>          if (CredentialsType.<em>USER</em>.equals(item.getType())) {<br>              users.add(item.getName());<br>          } else {<br>              groups.add(item.getName());<br>          }<br>      }<br>  }</pre><pre>  destination.setGroups(users);<br>  destination.setUsers(groups);<br>}</pre><p>Ok, above we solve our problem, but our code is doing too much stuff and its hard to change when the requirement will change. Moreover, we are not trendy because we are not using at Java Stream (Java 8 it is released in 2014, come on!!!) to iterate our list. So we can refactor our code in:</p><pre>public void myMethod(A source, B destination) {<br>    Set&lt;String&gt; users = new HashSet&lt;&gt;();<br>    Set&lt;String&gt; groups = new HashSet&lt;&gt;();</pre><pre>    source.getCredentials()<br>            .stream()<br>            .filter(Credentials::isActive)<br>            .forEach(item -&gt; {<br>                if (CredentialsType.<em>USER</em>.equals(item.getType())) {<br>                    users.add(item.getName());<br>                if (CredentialsType.<em>GROUP</em>.equals(item.getType())) {<br>                    groups.add(item.getName());<br>                }<br>            });</pre><pre>    destination.setGroups(users);<br>    destination.setUsers(groups);<br>}</pre><p>But nothing is changed, we just use a different API, but our code logic is still the same.</p><p><strong>PS: Always</strong> <strong>write a test before starting the refactoring in order to validate that the original behavior doesn’t change, otherwise a kitten will die!</strong></p><h3>Serious refactoring in Java</h3><p>Even though write less code is better, we are doing two things in the same piece of code, so we can make our code cleaner, just filling a list at a time.</p><pre>public void myMethod(A source, B destination) {</pre><pre>    Set&lt;String&gt; users = source.getCredentials()<br>        .stream()<br>        .filter(Credentials::isActive)<br>        .filter(it -&gt; CredentialsType.<em>USER</em>.equals(item.getType()))<br>        .map(item -&gt; item.getName())<br>        .collect(Collectors.<em>toSet</em>());</pre><pre>Set&lt;String&gt; groups = source.getCredentials()<br>        .stream()<br>        .filter(Credentials::isActive)<br>        .filter(it -&gt; CredentialsType.<em>GROUP</em>.equals(item.getType()))<br>        .map(item -&gt; item.getName())<br>        .collect(Collectors.<em>toSet</em>());</pre><pre>    destination.setGroups(users);<br>    destination.setUsers(groups);<br>}</pre><p>After we can extract a method to avoid duplications and to have a decent code.</p><pre>public void myMethod(A source, B destination) {<br>    destination.setGroups(extractFrom(source.getCredentials(), <br>            item -&gt; CredentialsType.<em>GROUP</em>.equals(item.getType())));<br>    destination.setUsers(extractFrom(source.getCredentials(), <br>            item -&gt; CredentialsType.<em>USER</em>.equals(item.getType())));<br>}</pre><pre>public Set&lt;String&gt; extractFrom(List&lt;Credentials&gt; credentials, Predicate&lt;Credentials&gt; predicate) {<br>    return credentials<br>            .stream()<br>            .filter(Credentials::isActive)<br>            .filter(predicate)<br>            .map(Credentials::getName)<br>            .collect(Collectors.<em>toSet</em>());<br>}</pre><p>Now, using our shining new method <strong>extractFrom </strong>its very simple to add new features in our method, for instance, if we want to collect adult users, we can simply add a line in our code.</p><pre>destination.setAdultUsers(extract(source.getCredentials(),<br>        item -&gt; item.getAge() &gt; 18<br>                &amp;&amp; CredentialsType.<em>USER</em>.equals(item.getType())));</pre><p>We already moved some responsibilities from one method to another, but, we can move the responsibility about the type of the credential, or if the user is Adult in the Credentials class and use a cool <strong>method reference</strong>:</p><pre>destination.setUsers(extractFrom(source.getCredentials(), <br>        Credentials::isUser //or ::isGroup or ::isAdult));</pre><p>We can do more refactoring? Of course! But for our target, it is enough.</p><h3>Kotlin can do it better</h3><p>In Koltin we can do even better, as shown below:</p><pre>fun myMethod(source: A, destination: B): B = destination.copy(<br>        groups = extractFrom(source.<em>credentials</em>)<strong>{ </strong>GROUP == <strong>it</strong>.<em>type</em><strong>}</strong>,<br>        users = extractFrom(source.<em>credentials</em>)<strong>{ </strong>USER == <strong>it</strong>.<em>type </em><strong>}</strong>,<br>        adultUsers = extractFrom(source.<em>credentials</em>)<strong>{ <br>                                   </strong>USER == <strong>it</strong>.<em>type </em>&amp;&amp; <strong>it</strong>.<em>age </em>&gt;= 18 <br>                                 <strong>}<br></strong>)<br></pre><pre>fun extractFrom(credentials: List&lt;Credentials&gt;,<br>                predicate: (Credentials) -&gt; Boolean) = credentials<br>        .<em>filter </em><strong>{ it</strong>.<em>isActive </em><strong>}<br>        </strong>.<em>filter </em><strong>{ </strong>predicate(<strong>it</strong>) <strong>}<br>        </strong>.<em>map </em><strong>{ it</strong>.<em>name </em><strong>}<br>        </strong>.<em>toSet</em>()</pre><p>The code above is exactly the same that we did in Java, but using some Kotlin features:</p><ul><li><a href="https://kotlinlang.org/docs/reference/lambdas.html?_ga=2.33368766.1202614984.1581266775-331827490.1581266775#it-implicit-name-of-a-single-parameter">Implicit name of a simple parameter</a>: we can remove unuseful code using the keyword “it” and <strong>improving code readability</strong>. This keyword stands for the default single parameter of a function, so we don’t have to declare it explicitly.</li><li><a href="https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter">Passing trailing lambdas</a>: in Kotlin we can pass a lambda expression outside function parameters when the last parameter of a function is a function, and if it is the only argument, the parentheses can be omitted entirely.</li><li><a href="https://kotlinlang.org/docs/reference/data-classes.html">Data classes</a>: are classes whose main purpose is to hold data and they provide useful methods like <em>copy</em> that can create a new copy of the object. The method accepts as parameters any field of the class, using <a href="https://kotlinlang.org/docs/reference/functions.html#named-arguments">named arguments</a>, so we can customize our copy, reaching <strong>immutability principle, </strong>because of our data class is immutable because it will use <em>val</em> modifier to define class fields<strong>:</strong></li></ul><pre>data class B(val users: Set&lt;String&gt;, val groups: Set&lt;String&gt;, val adultUsers: Set&lt;String&gt;)</pre><h3>Further reading</h3><p>In the past, I wrote two articles like that, unfortunately, they are in Italian, but there is a lot of code, so you can understand them even just by reading the code ;)</p><ul><li><a href="https://medium.com/@davidecerbo/how-difficult-can-it-ever-be-to-build-a-list-of-objects-in-java-and-kotlin-using-the-builder-fb0d0a8a5ca6">How difficult can it ever be to build a list of objects in Java and Kotlin using the builder…</a></li><li><a href="https://medium.com/@davidecerbo/kotlin-vs-java-maps-6dcb6f4f21cd">Kotlin vs. Java: Maps</a></li><li><a href="https://medium.com/@davidecerbo/kotlin-vs-java-fibonacci-d76c5b282ea">Kotlin vs. Java: Fibonacci</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=966e9d6ecbb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Structured concurrency in Kotlin]]></title>
            <link>https://davidecerbo.medium.com/kotlin-structured-concurrency-in-my-own-words-3f381c188fc9?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f381c188fc9</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Mon, 16 Dec 2019 12:45:49 GMT</pubDate>
            <atom:updated>2019-12-16T18:24:00.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBIop7oZn4tVvsC3NcDcYw.jpeg" /><figcaption>Photo by <a href="https://freeimages.com/photographer/ctechs-29846">Jeff Prieb</a> from <a href="https://freeimages.com/photographer/ctechs-29846">FreeImages</a></figcaption></figure><p>Studying about Kotlin Coroutine, I often read Structure concurrency but what it really means? <strong>Structured</strong> how many times do you hear this word about programming? <strong>Structured programming</strong>, is a programming paradigm born to improve code quality and clarity, by using structured control flow constructs of selection (if…then…elen) and repetition (while and for), block structures and subroutines. This concept born by some considerations made by Edsger W. Dijkstra in “<a href="http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html">Go To Statement Considered Harmful</a>”.</p><p>Basically we have to stop to write:</p><pre>10 i = 0<br>20 i = i + 10<br>30 PRINT &quot;i: &quot; + i<br>40 IF (i &lt; 100) GOTO 20</pre><p>In favor of:</p><pre>int i = 0;<br>while(i &lt; 100){ <br>   i = i + 10;<br>   print(&quot;i: &quot; + i);<br>}</pre><p>Because rely on a row index makes our software very hard to maintain, while programming using block structures and subroutine is very helpful when we need to modify our code.</p><p>Why we cannot do the same when we have to do concurrency programming? Martin Sústrik, the ZeroMQ creator, introduce this concept for the first time <a href="http://250bpm.com/blog:71">in his blog</a>, Roman Elizarov like his ideology and introduce this concept in <a href="https://medium.com/@elizarov/structured-concurrency-722d765aa952">Kotlin Coroutine</a> two years later. Go back to our example…</p><p>Let’s imagine a simple game where the winner is who plays more times in 500 milliseconds:</p><pre>fun main()  {<br>    var playerOne = AtomicInteger();<br>    var playerTwo = AtomicInteger();<br>    <em>thread </em><strong>{<br>        </strong><em>println</em>(&quot;Start match - ${Thread.currentThread().<em>name</em>}&quot;)<br>        <em>thread </em><strong>{<br>            </strong>(1..10).<em>forEach </em><strong>{<br>                </strong>Thread.sleep(Random.nextLong(10, 200))<br>                <em>println</em>(&quot;P1 $<strong>it</strong> - ${Thread.currentThread().<em>name</em>}&quot;)<br>                playerOne.incrementAndGet()<br>            <strong>}<br>        }<br>        </strong><em>thread </em><strong>{<br>            </strong>(1..10).<em>forEach </em><strong>{<br>                </strong>Thread.sleep(Random.nextLong(10, 200))<br>                <em>println</em>(&quot;P2 $<strong>it</strong> - ${Thread.currentThread().<em>name</em>}&quot;)<br>                playerTwo.incrementAndGet()<br>            <strong>}<br>        }<br>        </strong>Thread.sleep(500)<br>        Thread.currentThread().interrupt();<br>        <em>println</em>(&quot;End match! - ${Thread.currentThread().<em>name</em>}&quot;)<br>        when {<br>            playerOne.get() &gt; playerTwo.get() -&gt; <em>println</em>(&quot;P1 wins&quot;)<br>            playerOne.get() &lt; playerTwo.get() -&gt; <em>println</em>(&quot;P2 wins&quot;)<br>            playerOne.get() == playerTwo.get() -&gt; <em>println</em>(&quot;Draw!&quot;)<br>        }<br>    <strong>}<br>    </strong><em>println</em>(&quot;end - ${Thread.currentThread().<em>name</em>}&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ESWGWNTpaBRMYwWvSzlLA.gif" /></figure><p>As you can see in the console above the player continue playing because the interruption of parent thread doesn’t stop the children execution. Of course, we can fix it, but this isn’t so easy and the code will not so clear to understand. Thanks to Kotlin syntax our code is structured, <em>thread { … } seems a </em>syntactic construct, but it isn’t actually structured concurrency because <strong>the lifetime of a thread isn’t bound to a code block. </strong>So, we are violating concepts behind structured programming.</p><p>So let’s go with a refactoring using <strong>coroutine</strong>:</p><pre>fun main() = runBlocking {<br>    var playerOne = AtomicInteger();<br>    var playerTwo = AtomicInteger();<br>    launch {<br>        println(&quot;Start match - ${Thread.currentThread().name}&quot;)<br>        launch {<br>            (1..10).forEach {<br>                delay(Random.nextLong(10, 200))<br>                println(&quot;P1 $it - ${Thread.currentThread().name}&quot;)<br>                playerOne.incrementAndGet()<br>            }<br>        }<br>        launch {<br>            (1..10).forEach {<br>                delay(Random.nextLong(10, 200))<br>                println(&quot;P2 $it - ${Thread.currentThread().name}&quot;)<br>                playerTwo.incrementAndGet()<br>            }<br>        }<br>        delay(500)<br>        cancel()<br>        println(&quot;End match! - ${Thread.currentThread().name}&quot;)<br>        when {<br>            playerOne.get() &gt; playerTwo.get() -&gt; println(&quot;P1 wins&quot;)<br>            playerOne.get() &lt; playerTwo.get() -&gt; println(&quot;P2 wins&quot;)<br>            playerOne.get() == playerTwo.get() -&gt; println(&quot;Draw!&quot;)<br>        }<br>    }<br>    println(&quot;end - ${Thread.currentThread().name}&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kujXcfLDyiTu4UFbZwKwA.gif" /></figure><p>Now the players stop to play when the game ends!</p><p>So we reach our target about structured concurrency because using the <em>launch</em> syntactic construct the lifetime of a thread is bound to a code block and our code readability is awesome :)</p><p>This isn’t enough, another interesting feature of Structured concurrency is that the parent thread will complete only when all children complete.</p><pre>fun main() = runBlocking {<br>    launch {<br>        println(&quot;Start - ${Thread.currentThread().name}&quot;)<br>        launch {<br>            (1..5).forEach {<br>                delay(100)<br>                println(&quot;A $it - ${Thread.currentThread().name} &quot;)<br>            }<br>        }<br>        launch {<br>            (1..5).forEach {<br>                delay(200)<br>                println(&quot;B $it - ${Thread.currentThread().name} &quot;)<br>            }<br>        }<br>    }.invokeOnCompletion {<br>        println(&quot;Complete! - ${Thread.currentThread().name}&quot;)<br>    }<br>    println(&quot;End main method - ${Thread.currentThread().name}&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*CMHzhdSCedzVpjAc85c-0Q.gif" /></figure><p>In the example above the parent <em>launch</em> construct will print “Complete! — main” only after the completion of all children tasks.</p><p>We can do that in plain Java? Not yet, but Fiber is coming:</p><p><a href="https://wiki.openjdk.java.net/pages/viewpage.action?pageId=46956975">Structured Concurrency</a></p><p>Do you wish to learn more? Visit this forum to find a lot of useful resources and discussion about Structured concurrency:</p><p><a href="https://trio.discourse.group/c/structured-concurrency">Structured concurrency</a></p><h3>More on Kotlin Coroutine</h3><ul><li><a href="https://medium.com/@davidecerbo/playing-with-kotlin-flows-72370fc00e51">Playing with Kotlin Flows</a></li><li><a href="https://medium.com/@davidecerbo/backpressure-in-kotlin-flows-9324d86c964e">Backpressure in Kotlin Flows</a></li></ul><h3>Further reading</h3><ul><li><a href="http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html">Go To Statement Considered Harmful</a></li><li><a href="http://250bpm.com/blog:71">250bpm</a></li><li><a href="https://medium.com/@elizarov/structured-concurrency-722d765aa952">Structured concurrency</a></li><li><a href="https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/">Notes on structured concurrency, or: Go statement considered harmful</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f381c188fc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpressure in Kotlin Flows]]></title>
            <link>https://davidecerbo.medium.com/backpressure-in-kotlin-flows-9324d86c964e?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/9324d86c964e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[reactive]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 17:11:13 GMT</pubDate>
            <atom:updated>2019-12-30T11:48:10.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Back-pressure in Kotlin Flows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IJD66y1SCDv9IJs8.jpg" /><figcaption>With back-pressure, your tasks become polite and they wait for their turn.</figcaption></figure><blockquote>Do you want more information about Kotlin Flow? <a href="https://medium.com/@davidecerbo/playing-with-kotlin-flows-72370fc00e51">Read this first</a>!</blockquote><p>This is one of the best features of reactive programming and it is borrowed from fluid dynamics. Wikipedia defines it as:</p><blockquote>Resistance or force opposing the desired flow of fluid through pipes</blockquote><p>So, in our domain, it means to control the data flow to be sure that the load doesn’t kill our application. Traditionally reactive programming libraries have some dedicate feature but with Flows the back-pressure management is achieved using Kotlin <em>suspending functions</em>. All things in Flows are marked with <em>suspend</em> modifier, so if there is a high load, the execution will be suspended without blocking any thread, until the application is ready to accept more elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceSJw4gauK57b0HLpmZmng.jpeg" /></figure><p>Let’s stop thinking about this way too serious definition and let’s start thinking about a funnier definition! Let’s imagine that you have an oven and you would like to bake your muffin. If you have only 4 spots in your oven, you can bake only 4 muffins at once. If you try to bake all muffins together, you need more electricity and, if you are lucky, you will burn your sweet, or if you are unlucky, you can break your oven. Any way you think that you are going faster, but it isn’t true and it is very risky. Now think that your oven is a software installed in a server with 4 CPUs, electricity is memory usage, and think what you are doing to your poor application!</p><p>Not so clear? Let’s go with a little example! For instance, look at the simple flow below that emits one element every second:</p><pre>fun currTime() = System.currentTimeMillis()<br>fun threadName() = Thread.currentThread().<em>name</em>var <em>start</em>: Long = 0<br><br>fun emitter(): Flow&lt;Int&gt; =<br>        (1..5)<br>                .<em>asFlow</em>()<br>                .<em>onStart </em><strong>{ </strong><em>start </em>= <em>currTime</em>() <strong>}<br>                </strong>.<em>onEach </em><strong>{<br>                    <em>delay</em>(1000)<br></strong>                    <em>print</em>(&quot;Emit $<strong>it</strong> (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>                <strong>}</strong></pre><p>and collects values in 3 seconds using the code below:</p><pre>@InternalCoroutinesApi<br>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{<br>   </strong>val time = <em>measureTimeMillis </em><strong>{<br>      </strong><em>emitter</em>()<br>        .<em>collect </em><strong>{<br>           </strong><em>print</em>(&quot;\nCollect $<strong>it</strong> starts (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br><strong>           <em>delay</em>(3000)<br></strong>           <em>println</em>(&quot;Collect $<strong>it</strong> ends (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>       <strong>}<br>    }<br>    </strong><em>print</em>(&quot;\nCollected in $time ms&quot;)<br><strong>}</strong></pre><p>The example needs around 20 seconds (3s * 5 + 1s * 5) to end, especially because the element collecting is very slow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UX_E2rOHmmglRokGEKhpCg.gif" /></figure><p>The example above is a clear simulation of a situation where the collecting is slower than emission and so we need a <strong>back-pressure</strong> mechanism, and as we can see, this is inside the Flow nature.</p><p>The first idea that could come in our mind can be to move the fast emit operation in another thread, so the slow collect phase can take its time:</p><pre>@InternalCoroutinesApi<br>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{<br>    </strong>val time = <em>measureTimeMillis </em><strong>{<br>        </strong><em>emitter</em>()<br><strong>                .<em>flowOn</em>(Dispatchers.Default)<br></strong>                .<em>collect </em><strong>{<br>...</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2U6zSSj-_AUa0ft2SzFFFw.gif" /></figure><p>We can do better? Of course, for instance, we can decide to buffer the collecting, so we don’t rely on a new thread instance, with all downsides about memory and context switching:</p><pre>@InternalCoroutinesApi<br>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{<br>   </strong>val time = <em>measureTimeMillis </em><strong>{<br>      </strong><em>emitter</em>()<br><strong>        .buffer()<br></strong>        .<em>collect </em><strong>{<br>           </strong><em>print</em>(&quot;\nCollect $<strong>it</strong> starts (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>           <em>delay</em>(3000)<br>           <em>println</em>(&quot;Collect $<strong>it</strong> ends (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>       <strong>}<br>    }<br>    </strong><em>print</em>(&quot;\nCollected in $time ms&quot;)<br><strong>}</strong></pre><p>So the new output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NN7fV17OxyHH9MCG78JL1Q.gif" /></figure><p>As you can see above, when the collector is busy, the program starts the buffering and the collecting starts again after two emissions when the first collect method invocation ends. But, more importantly, the flow needs only ~16 seconds to be executed, like the solution that relies on a new thread instance.</p><p>In some scenarios, we can decide to lose data to be even faster. In this case, we can <strong>conflate</strong> our emission by missing some elements.</p><pre>@InternalCoroutinesApi<br>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{<br>   </strong>val time = <em>measureTimeMillis </em><strong>{<br>      </strong><em>emitter</em>()<br><strong>        .conflate()<br></strong>        .<em>collect </em><strong>{<br>           </strong><em>print</em>(&quot;\nCollect $<strong>it</strong> starts (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>           <em>delay</em>(3000)<br>           <em>println</em>(&quot;Collect $<strong>it</strong> ends (${<em>currTime</em>() - <em>start</em>}ms) &quot;)<br>       <strong>}<br>    }<br>    </strong><em>print</em>(&quot;\nCollected in $time ms&quot;)<br><strong>}</strong></pre><p>As you can see below, only the last element emitted before that the collector became free it was collected. So, we miss emissions 2 and 4, but the flow needs only ~10 seconds to be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZntgvN64BC5rFbEYHb57aA.gif" /></figure><h3>More on Kotlin Coroutine</h3><ul><li><a href="https://medium.com/@davidecerbo/kotlin-structured-concurrency-in-my-own-words-3f381c188fc9">Playing with Structured concurrency in Kotlin</a></li><li><a href="https://medium.com/@davidecerbo/playing-with-kotlin-flows-72370fc00e51">Playing with Kotlin Flows</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9324d86c964e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Kotlin Flows]]></title>
            <link>https://davidecerbo.medium.com/playing-with-kotlin-flows-72370fc00e51?source=rss-96739cbc436------2</link>
            <guid isPermaLink="false">https://medium.com/p/72370fc00e51</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Davide Cerbo]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 22:37:16 GMT</pubDate>
            <atom:updated>2019-12-30T11:49:17.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smexl8hCPfWSp2HiWfdApw.jpeg" /></figure><p>Nowadays we are listening to words <strong>Reactive programming</strong> every day, and many projects, like Spring, are adding reactive support to their libraries.</p><p>If you are a Java or Kotlin programmer you usually hear frameworks like <a href="https://github.com/ReactiveX/RxJava">RxJava</a>, <a href="https://www.reactive-streams.org/">Reactive Streams</a>, and <a href="https://projectreactor.io/">Reactor</a>, but with Kotlin there is a new alternative provided by the language: <strong>Flows</strong>!</p><p>Flows are basically <strong>asynchronous streams that relay on coroutines</strong> for their execution. When we are talking about asynchronous streams we can have:</p><ul><li><strong>hot stream</strong>: the stream is always active and the subscription to the flow starts from the point where is the emission of data on the stream. Usually, you can think about a movie on television, you start to see it starting from when you turn on the TV, not from the beginning.</li><li><strong>cold stream</strong>: the stream always starts from the beginning. Coming back to the movie, a cold stream is when you are seeing it from Netflix (or your favorite streaming platform) and you will start it from the beginning. Generally, we can say that a <strong>cold stream is lazy</strong>.</li></ul><p><strong>Flows are cold streams</strong>, very similar to sequences, but they allow suspending and, as I said before, they are asynchronous.</p><p>For those who don’t know c<a href="https://en.wikipedia.org/wiki/Coroutine">oroutines</a>, they provide an alternative to thread blocking using <em>suspension</em>. This means that the caller thread will not be blocked while it waits for resources, but it will be suspended, without block anything (i.g. our UI), while it is waiting.</p><h3>Table of contents</h3><ul><li><a href="#591f">Flows anatomy</a></li><li><a href="#e5b2">Flows lifecycle</a></li><li><a href="#3154">Intermediate flow operators</a></li><li><a href="#ee91">Error handling</a></li><li><a href="#ee91">Backpressure</a></li><li><a href="#14fd">Testing</a></li><li><a href="#53bb">Integration with existing libraries</a></li><li><a href="#acca">Resources</a></li></ul><h3>Flows anatomy</h3><p>The anatomy of a flow statement is very easy:</p><pre>flow {<br>   emit(&quot;Hello world&quot;)<br>}.collect(...)</pre><p>The first row <strong>creates the flow </strong>(builder), the second row <strong>emits something</strong> on the flow, and the third row starts the flow and <strong>collects elements </strong>(terminal operation). Because flows are lazy, these don’t start until the terminal operation is invoked.</p><h3>Flows lifecycle</h3><p>Flows API provides some method that can be invoked during the lifecycle of a flow</p><pre><em>flow </em><strong>{<br>    </strong>(1..5).<em>forEach </em><strong>{<br>        </strong>delay(1000) //delay the emission<br>        emit(<strong>it</strong>)<br>        if (<strong>it </strong>== 2) throw RuntimeException(&quot;Error on $<strong>it</strong>&quot;)<br>    <strong>}<br>}<br>        </strong>.<em>onEach </em><strong>{ </strong><em>println</em>(&quot;On each $<strong>it</strong>&quot;) <strong>}<br>        </strong>.<em>onStart </em><strong>{ </strong><em>println</em>(&quot;Starting flow&quot;) <strong>}<br>        </strong>.<em>onCompletion </em><strong>{ </strong><em>println</em>(&quot;Flow completed&quot;) <strong>}<br>        </strong>.<em>catch </em><strong>{ </strong>ex <strong>-&gt; </strong><em>println</em>(&quot;Exception message: ${ex.message}&quot;) <strong>}<br>        </strong>.<em>toList</em>()</pre><p>In the example above I build a flow that emits numbers from 1 to 5, every second, the expected output will be:</p><pre>Starting flow<br>On each 1<br>On each 2<br>Flow completed<br>Exception message: Error on 2</pre><p>As you can see, I print something in the console at the beginning and at the end of the flow, for each emission, and I catch the error after the second emission. The flow will complete where there is an exception.</p><p>The method <em>toList</em> is a terminal operation helpful to collect all values in a list.</p><h3>Intermediate flow operators</h3><p>As for other types of streams, I can transform the flow using the <em>map </em>method<em>:</em></p><pre>(1..5)<br>        .<em>asFlow</em>()<br>        .<em>map </em><strong>{ it </strong>* 2 <strong>}<br>        </strong>.<em>onEach </em><strong>{ </strong><em>println</em>(&quot;On each $<strong>it</strong>&quot;) <strong>}<br>        </strong>.<em>toList</em>()</pre><p>The returned list will be <em>2, 4, 6, 8, 10</em>.</p><p>Or flatMapConcat if I would flat flow of flows:</p><pre>(1..5)<br>        .<em>asFlow</em>()<br>        .<em>flatMapConcat </em><strong>{<br>            </strong><em>flow </em><strong>{<br>                </strong>emit(<strong>it</strong>)<br>                emit(<strong>it </strong>* <strong>it</strong>)<br>            <strong>}<br>        }<br>        </strong>.<em>onEach </em><strong>{ </strong><em>println</em>(&quot;On each $<strong>it</strong>&quot;) <strong>}<br>        </strong>.<em>toList</em>()</pre><p>The result will be <em>1, 1, 2, 4, 3, 9, 4, 16, 5, 25.</em></p><p>These operators are for transforming, but there were more operators for limiting the size of the emission, like <em>drop</em>, to skip firsts data emitted:</p><pre>(1..5)<br>        .<em>asFlow</em>()<br>        .drop(2) //skips first two emitted integers<strong><br>        </strong>.<em>toList</em>() //the result will be [3, 4, 5]</pre><p>Or, like <em>take</em>, to terminate the flow after an amount of data emitted:</p><pre>(1..5)<br>        .<em>asFlow</em>()<br>        .take(2) //takes first two emitted integers<strong><br>        </strong>.<em>toList</em>() //the result will be [1, 2]</pre><h3>Error handling</h3><p>In order to handle error on Flows, we can use the flow operator catch to log a message, as in the lifecycle example above, or we can resume another flow using <em>emit, </em>to emit a single element at once<em>, </em>or <em>emitAll </em>to emit a whole flow:</p><pre>(1..5).<em>asFlow</em>().<em>onEach </em><strong>{<br>    </strong>if (<strong>it </strong>== 3) throw RuntimeException(&quot;Error on $<strong>it</strong>&quot;)<br><strong>}</strong>.<em>catch </em><strong>{<br>    </strong><em>emitAll</em>((99..100).<em>asFlow</em>())<br><strong>}</strong>.<em>toList</em>()</pre><p>The example below will return [1, 2, 99, 100].</p><p>To handle error we can also use retry or <em>retryWhen</em> operator:</p><pre>(1..5).<em>asFlow</em>().<em>onEach </em><strong>{<br>    </strong>if (<strong>it </strong>== 3) throw RuntimeException(&quot;Error on $<strong>it</strong>&quot;)<br><strong>}<br>        </strong>.<em>onEach </em><strong>{ </strong><em>println</em>(&quot;Emitting $<strong>it</strong>&quot;) <strong>}<br>        </strong>.<em>retryWhen </em><strong>{ </strong>cause, attempt <strong>-&gt;<br>            </strong><em>println</em>(&quot;cause $cause attempt, $attempt&quot;)<br>            attempt &lt; 1<br>        <strong>}</strong>.<em>toList</em>()</pre><p>In the example above in the console we will see:</p><pre>Emitting 1<br>Emitting 2<br>cause java.lang.RuntimeException: Error on 3, attempt 0<br>Emitting 1<br>Emitting 2<br>cause java.lang.RuntimeException: Error on 3, attempt 1</pre><p>And finally an exception with the message “Error on 3” will be thrown.</p><p>So, the flow will be retried 2 times before the failure. The flow is cold, so it will be executed, always, from the beginning.</p><p>Comparing to the traditional reactive framework there is a huge difference. For instance in Project Reactor, the exception will be shown only if it is explicitly defined as an onError function, otherwise, the exception will be ignored.</p><h3>Backpressure</h3><p>This is one of the best features of reactive programming and it is borrowed from fluid dynamics. Wikipedia defines it as:</p><blockquote>Resistance or force opposing the desired flow of fluid through pipes</blockquote><p>Want to know more? <a href="https://medium.com/@davidecerbo/backpressure-in-kotlin-flows-9324d86c964e">Read this post</a>!</p><h3>Testing</h3><p>Testing is a crucial practice in our daily life. To try the example above I wrote this <a href="https://github.com/jesty/rsocket-kotlin-demo/blob/master/flow-examples/src/test/kotlin/com/github/jesty/flowexamples/FlowExamplesTest.kt">test class</a> using <a href="https://github.com/willowtreeapps/assertk">AssertK</a>, an assertion library for Kotlin inspired by AssertJ.</p><p>The use of this library is very simple:</p><pre>@Test<br>fun `map value test`() = <em>runBlocking </em><strong>{<br>    </strong><em>assertThat </em><strong>{<br>        </strong>(1..5)<br>                .<em>asFlow</em>()<br>                .<em>map </em><strong>{ it </strong>* 2 <strong>}<br>                </strong>.<em>onEach </em><strong>{ </strong><em>println</em>(&quot;On each $<strong>it</strong>&quot;) <strong>}<br>                </strong>.<em>toList</em>()<br>    <strong>}</strong>.<em>isSuccess</em>().<em>containsExactly</em>(2, 4, 6, 8, 10)<br><strong>}</strong></pre><p>Before all, I need to use <em>runBlocking, </em>because coroutines are asynchronous and my test will end before the code execution. Inside that, I use <em>assertThat</em> to wrap the code I’m testing, and after I will verify that the result is what I’m expecting. In the <a href="https://github.com/willowtreeapps/assertk">official documentation</a> and on the <a href="https://github.com/jesty/rsocket-kotlin-demo/blob/master/flow-examples/src/test/kotlin/com/github/jesty/flowexamples/FlowExamplesTest.kt">example code that I provided on Github</a>, you can find more examples.</p><h3>Integration with existing libraries</h3><p>Today there is a lot of libraries that provide a reactive implementation, someone is using Reactor, others are using RxJava, not so many are using Kotlin Flows. This could be an issue, but, fortunately, Kotlin&#39;s power comes in our help! Using extension function it is possible to convert a Flow to Reactor Flux, or to a RxJava Flowable, and vice-versa:</p><pre>//<a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactor">Project Reactor</a><br>val reactorFlux: Flux&lt;String&gt; = flow { ... }.asFlux()<br>val fluxToFlow: Flow&lt;String&gt; = reactorFlux.asFlow()</pre><pre>//<a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/rx2">RxJava</a><br>val rxjavaFlowable: Flowable&lt;String&gt; = flow { ... }.asFlowable()<br>val flowableToFlow: Flow&lt;String&gt; = rxjavaFlowable.asFlow()</pre><pre>//<a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive">Reactive Streams</a><br>val rStreamFlowable: Publisher&lt;String&gt; = flow { ... }.asPublisher()<br>val flowableToFlow: Flow&lt;String&gt; = rStreamFlowable.asFlow()</pre><p>This could be very useful in order to reuse existing code and libraries.</p><p>Just remember to add the right dependency:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.jetbrains.kotlinx&lt;/groupId&gt;<br>   &lt;artifactId&gt;kotlinx-coroutines-reactor&lt;/artifactId&gt;<br>   &lt;version&gt;${kotlinx-coroutines.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;!-- OR --&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.jetbrains.kotlinx&lt;/groupId&gt;<br>   &lt;artifactId&gt;kotlinx-coroutines-rx2&lt;/artifactId&gt;<br>   &lt;version&gt;${kotlinx-coroutines.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;!-- OR --&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.jetbrains.kotlinx&lt;/groupId&gt;<br>   &lt;artifactId&gt;kotlinx-coroutines-reactive&lt;/artifactId&gt;<br>   &lt;version&gt;${kotlinx-coroutines.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>More on Kotlin Coroutine</p><ul><li><a href="https://medium.com/@davidecerbo/backpressure-in-kotlin-flows-9324d86c964e">Backpressure in Kotlin Flows</a></li><li><a href="https://medium.com/@davidecerbo/kotlin-structured-concurrency-in-my-own-words-3f381c188fc9">Playing with Structured concurrency in Kotlin</a></li></ul><h3>Resources</h3><ul><li><a href="https://github.com/jesty/rsocket-kotlin-demo/blob/master/flow-examples/src/test/kotlin/com/github/jesty/flowexamples/FlowExamplesTest.kt">jesty/rsocket-kotlin-demo</a></li><li><a href="https://medium.com/@elizarov/simple-design-of-kotlin-flow-4725e7398c4c">Simple design of Kotlin Flow</a></li><li><a href="https://medium.com/@elizarov/cold-flows-hot-channels-d74769805f9">Cold flows, hot channels</a></li><li><a href="https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761">Blocking threads, suspending coroutines</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72370fc00e51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>