<?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 José Braz on Medium]]></title>
        <description><![CDATA[Stories by José Braz on Medium]]></description>
        <link>https://medium.com/@josehhbraz?source=rss-b06bf557dc4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HoVh9wu0lFGdWUUYmzKLQQ.jpeg</url>
            <title>Stories by José Braz on Medium</title>
            <link>https://medium.com/@josehhbraz?source=rss-b06bf557dc4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:19:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josehhbraz/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 Avoid Singleton Pattern in Kotlin and Test]]></title>
            <link>https://medium.com/@josehhbraz/how-to-avoid-singleton-pattern-in-kotlin-and-test-e828258813a?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e828258813a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Tue, 16 May 2023 09:54:22 GMT</pubDate>
            <atom:updated>2023-05-16T09:54:22.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to avoid singleton pattern in Kotlin and test</h3><h4>Learn how to refactor the Kotlin object into a class with no more changes in the project and prepare to test this class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1vijHE4GhEc2IJEW" /><figcaption>Photo by <a href="https://unsplash.com/ja/@grakozy?utm_source=medium&amp;utm_medium=referral">Greg Rakozy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Singleton pattern provides a straightforward method to obtain a single instance of a class across multiple classes. It is commonly used for implementing manager or service classes, providing a simple and consistent way to access them.</p><h4>The problem with the singleton pattern</h4><p>A singleton class (known as object in Kotlin) is difficult to test because the class state is remembered across test cases, which requires the tester to explicitly clear the state before each test ends. Another problem is that the objects don&#39;t have custom constructors, which are used to inject mock implementations to simulate a specific behavior or scenario.</p><p>Suppose we have a singleton, creatively named Singleton, which depends on an interface called Dependency with only one implementation, DependencyImpl. We also have a CoroutineScope with a Main dispatcher and a single function called foo, which launches a coroutine and prints the output of the doIt function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6342d4d4ddedd1baff9a3913d91b8e40/href">https://medium.com/media/6342d4d4ddedd1baff9a3913d91b8e40/href</a></iframe><p>How we can test it? Suppose a simple test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d57692a01cd78b227b5fb9e5cf3128/href">https://medium.com/media/b5d57692a01cd78b227b5fb9e5cf3128/href</a></iframe><p>The fixed CoroutineScope of the Singleton crashes the test run with the output:</p><blockquote>Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used</blockquote><p>Okay, while using Dispatchers.setMain can help with changing the dispatcher, it doesn&#39;t solve the injection problem and dispatcher control.</p><h4>Kotlin solves the problem</h4><p>The good news is that Kotlin allows us to refactor the Singleton without changing the rest of the code that depends on it! First, we need to extract the interface of the Singleton and refactor the object to a class, receiving the dependencies in the primary constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b91195493f4170a9a6d69212b324e82e/href">https://medium.com/media/b91195493f4170a9a6d69212b324e82e/href</a></iframe><p>In Kotlin, we can provide a default implementation of an interface that can be used as a singleton. We create an instance of SingletonImpl with the same values as the original Singleton class. The default implementation of the interface is specified with the companion object keyword inside the interface, and provided with the by delegate pattern supported by Kotlin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c89a839413056a8302dfe6fe6d694b/href">https://medium.com/media/81c89a839413056a8302dfe6fe6d694b/href</a></iframe><p>After that, we can test the SingletonImpl by injecting a test scope and a mocked version of Dependency. The new version of the test creates an instance of SingletonImpl that only exists while this test is running. This avoids the need to clear the state before the test ends. Since the TestScope is used instead of Main, this test does not crash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49305fea1d807d5b50bb814abfdd7536/href">https://medium.com/media/49305fea1d807d5b50bb814abfdd7536/href</a></iframe><h4>Conclusion</h4><p>By using this approach, we can refactor an object and control its dependencies to test it in different scenarios. The rest of the code that depends on this object does not need to change and will retain the same behavior after the refactoring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e828258813a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SharedFlow Consumer Sensitive in Kotlin]]></title>
            <link>https://medium.com/better-programming/sharedflow-consumer-sensitive-in-kotlin-724069fd4358?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/724069fd4358</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 21:33:41 GMT</pubDate>
            <atom:updated>2022-11-05T19:48:42.548Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using a FileObserver example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MbF4BQSBWeJOiWFs" /><figcaption>Photo by <a href="https://unsplash.com/@andirieger?utm_source=medium&amp;utm_medium=referral">Andi Rieger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes, we need to model a resource as a SharedFlow in order to consume changes with nice Kotlin support.</p><p>For example, a flow that gets all changes in a file using <a href="https://developer.android.com/reference/android/os/FileObserver.html">FileObserver</a> or subscribes to a web feed to get news and update the UI. In all these cases, we need a way to open and close this resource to not spend battery or network unnecessarily (mobile device users hate this).</p><p>Now imagine if it were possible to know how many flow collectors are active and when they change. The <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-shared-flow/subscription-count.html">subscriptionCount</a> of MutableSharedFlow is exactly what we need!</p><p>I create a helper function to collect the subscriptionCount and trigger callbacks related to whether there are collecting or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c56f3a66d571cf32f07a4761077e76c/href">https://medium.com/media/7c56f3a66d571cf32f07a4761077e76c/href</a></iframe><p>Note that the onActive only runs if it is the first time or if the onInactive is <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/">started or completed</a>. In the other case, the onInactive is only called if the onActive has already been called. Their tests ensure that the same event will not be called twice in a row.</p><p>Also, note that before an event is launched the job of the last event is canceled. This is a performance optimization but needs to be observed carefully. If you need to execute some important thing that shouldn’t be canceled, please run this in a separate <a href="https://kotlinlang.org/docs/cancellation-and-timeouts.html#run-non-cancellable-block">(NonCancelable) coroutine context</a>.</p><p>We can generalize the listenerSubscribers method using an interface, called FlowBinder, to listen to these events and do something interesting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eabe2f21cbab92278cca35b8f71bbf04/href">https://medium.com/media/eabe2f21cbab92278cca35b8f71bbf04/href</a></iframe><p>Back to the FileObserver mentioned above. Every time no consumer is detected, the method onInactive is called, and it is necessary to stop watching for changes in the file. In the other case, when a first consumer is detected, the method onActive is called and we need to start watching for file events. Let’s see the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5508c500b454c0a60457f4c38c3f53f9/href">https://medium.com/media/5508c500b454c0a60457f4c38c3f53f9/href</a></iframe><p>For example, this can be used in a ViewModel like below, and it can execute some business logic with these file events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e49eba90115dc8aca3e87627e610b8/href">https://medium.com/media/f7e49eba90115dc8aca3e87627e610b8/href</a></iframe><h3>Conclusion</h3><p>The FileObserver is just an example of what the FlowBinder can do.</p><p>Feel free to share other use cases for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724069fd4358" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/sharedflow-consumer-sensitive-in-kotlin-724069fd4358">SharedFlow Consumer Sensitive in Kotlin</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspend Mediator — A simple way to communicate between coroutines in Kotlin]]></title>
            <link>https://medium.com/better-programming/suspend-mediator-a-simple-way-to-communicate-between-coroutines-in-kotlin-8d882eab0579?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d882eab0579</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 19:21:33 GMT</pubDate>
            <atom:updated>2022-10-27T19:09:28.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>Suspend Mediator — A Simple Way To Communicate Between Coroutines in Kotlin</h3><h4>Learn how to make simple WebSocket data sources with suspend functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CwzKkLYbGVEbTKjP" /><figcaption>Photo by <a href="https://unsplash.com/@zlucerophoto?utm_source=medium&amp;utm_medium=referral">Zach Lucero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this story, we will learn how to communicate different coroutines and use them to implement a remote data source with functions that look like a local function. These functions are a request returning response using WebSocket under the cloth.</p><h3>Motivation</h3><p>When I was writing a data source that internally uses a WebSocket connection, I noticed the send/receive socket pattern increases the software complexity and difficult maintainability. Send a request, and receiving the response in another part of the code forces the programmer to declare temporary variables to use in the response code.</p><p>Imagine if it was possible to send the request and suspend it until the response has been received and then resume it. Like the code below, the data source provides a nice suspend login function that returns the result of the login (full code at the end):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cddb71453ed260dfeb2075df87bb1c74/href">https://medium.com/media/cddb71453ed260dfeb2075df87bb1c74/href</a></iframe><h4>The SuspendMediator solves the problem</h4><p>Well, with SuspendMediator, it is possible! SuspendMediator is my implementation with only two methods: suspend and resume.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c3d25d7cf72ccde0452ae6f74befc40/href">https://medium.com/media/1c3d25d7cf72ccde0452ae6f74befc40/href</a></iframe><p>Note that the two functions receive a key to identify the request and the response exclusively. Suppose that request has a message identifier sent back on the response. This identifier can be the key to this message. The more “Unique” the key is, the more parallel requests can be because duplicate keys need to await in the request queue. This restriction is necessary for the SuspendMediator to know who to match uniquely the request sent with the response received.</p><h4>Implementation</h4><p>The SuspendMediator can have several implementations, with a queue for requests or not, with request/queue timeouts, and so on.</p><p>The queue of requests is used to cache requests with the same key or avoid parallel requests:</p><ul><li>NO QUEUE: Executions with different keys can be in parallel, but when the SuspendMediator detects a duplicate key, throws an error on suspend method.</li><li>ENQUEUE SAME KEY: Executions with different keys can be in parallel and enqueue duplicates key.</li><li>ENSURE ORDER: Avoid executions in parallel. It sends them one by one, awaiting the response in order.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4ceaefefa8ac996fc608bd06b3b39a3/href">https://medium.com/media/d4ceaefefa8ac996fc608bd06b3b39a3/href</a></iframe><p>We can have two types of timeout:</p><ul><li>Queue Timeout: The timeout is used when we have duplicate keys, and it is necessary to await in a queue to do the request.</li><li>Request Timeout: The timeout used to avoid awaiting a response that will never be received.</li></ul><p>Enough of the rambling. Show me the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/004cc3f4a7cc17f2a893b520d5750039/href">https://medium.com/media/004cc3f4a7cc17f2a893b520d5750039/href</a></iframe><h3>Examples Using SuspendMediator</h3><p>The main objective of SuspendMediator is to communicate between coroutines. Suppose a ping pong of three coroutines multiplies a number by two multiple times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6664164aa6f70b6a492b648edf9756/href">https://medium.com/media/bf6664164aa6f70b6a492b648edf9756/href</a></iframe><p>Output:</p><pre>Coroutine 1 - result1 Success(5)<br>Coroutine 2 - result2 Success(10)<br>Coroutine 3 - result3 Success(20)<br>Coroutine 1 - result4 Success(40)</pre><p>The coroutine 1 suspends with key 1 until coroutine 2 resumes this key with the value 5. Coroutine 1 resumes receiving the value and sends double this value with key 2. The value of key 3 is produced in coroutine 2 and sent to coroutine 3, and so on. Note that the SuspendMediator is not a producer/consumer but a way to communicate bidirectionally between coroutines.</p><p>The more interesting example is using the action callback of suspend function. When the action is called and returns true, it is guaranteed that the key is ready for another coroutine call to resume with this key.</p><p>Backing to the login example at the start of the story, imagine this simple login string protocol:</p><pre>Request: 1|username|password<br>Response: 1|loginResult</pre><p>Note that the first field represents the type of message (Login) that, in this example, has the value of 1, and we can use this as a Key of the message. The protocol can be implemented using sealed classes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d924e1324eab80b6f7fb5016752c39/href">https://medium.com/media/89d924e1324eab80b6f7fb5016752c39/href</a></iframe><p>Let’s see the DataSource example code using the SuspendMediator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/decc4f5edb74b0207039eeab31a80377/href">https://medium.com/media/decc4f5edb74b0207039eeab31a80377/href</a></iframe><p>When the login function is called, the function suspends until the queuedSuspendMediator has no key of value 1 in the queue because queueMode equals ENQUEUE_SAME_KEY. In the simple case, the queue is empty or does not have key 1, so no suspension is needed.</p><p>After that, the WebSocket sendMessage is called with the value of LoginRequest. When the server responds, the listener parses the message and calls the resume function with the LoginResult message.</p><h3>Conclusion</h3><p>With the SuspendMediator, we can write simpler codes with less complexity of temporary variables for the request and response messages. WebSocket DataSource is one of many use cases of SuspendMediator.</p><p>Thanks for reading. Stay tuned for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d882eab0579" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/suspend-mediator-a-simple-way-to-communicate-between-coroutines-in-kotlin-8d882eab0579">Suspend Mediator — A simple way to communicate between coroutines in Kotlin</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Map in Flow — Kotlin]]></title>
            <link>https://medium.com/@josehhbraz/parallel-map-in-flow-kotlin-f9735c9dc237?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9735c9dc237</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 01:30:59 GMT</pubDate>
            <atom:updated>2022-09-04T01:30:59.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parallel Map in Flow — Kotlin</h3><h4>Using a set of flow operations to create a parallel map operator as a Flow extension function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4drW47emQmeOj_5f" /><figcaption>Photo by <a href="https://unsplash.com/@scw1217?utm_source=medium&amp;utm_medium=referral">Suzanne D. Williams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With Flow parallel map we can do transformations using more than one thread and get the result in the original order. For heavy and slow transformations, parallel map achieve better results and consume less time.</p><p>After all, we need to know that the standard flow map operation runs in the same context as the collect operation, take a look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebad533512c4e8b4fe879bd64057c9a5/href">https://medium.com/media/ebad533512c4e8b4fe879bd64057c9a5/href</a></iframe><p>Output:</p><pre>[CoroutineId(2), “coroutine#2”, Dispatchers.Default]<br>A<br>[CoroutineId(2), “coroutine#2”, Dispatchers.Default]<br>B<br>[CoroutineId(2), “coroutine#2”, Dispatchers.Default]<br>C<br>[CoroutineId(3), “coroutine#3”, Dispatchers.IO]<br>A<br>[CoroutineId(3), “coroutine#3”, Dispatchers.IO]<br>B<br>[CoroutineId(3), “coroutine#3”, Dispatchers.IO]<br>C</pre><p>Note that although we collect flow on multithread scope, the map runs sequentially one by one, from the map to the collect method. Using a map with the <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/buffer.html">buffer</a> flow operation gives us a better result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d6b06a4cd39aa5f51945b3c905a129/href">https://medium.com/media/52d6b06a4cd39aa5f51945b3c905a129/href</a></iframe><p>Output:</p><pre>1A<br>1B<br>1C<br>2A<br>2B<br>2C</pre><p>With buffer operation, all elements are mapped first and then collected. This map runs on other coroutine but isn’t parallel. We need to run map code on a background thread and get the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce6446eebcd4c87151b2b9a860fe26b/href">https://medium.com/media/8ce6446eebcd4c87151b2b9a860fe26b/href</a></iframe><p>Output:</p><pre>Start map of 1 at 20:56:54.077634Z<br>Start map of 2 at 20:56:54.081994Z<br>Start map of 3 at 20:56:54.082103Z<br>Collected 2 at 20:56:57.089032Z<br>Collected 4 at 20:56:57.089306Z<br>Collected 6 at 20:56:57.089383Z</pre><p>We use two map operations. The first one maps to the Deferred job (with async operator) and the second awaits the result to conclude the map. All maps are running in parallel only if the collect coroutine context has a pool of threads. To enable collect runs on any context and even so the map operation run in parallel we can use <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.html">flowOn</a> operator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fbcf1aaae2f1784e00aabcaa5338922/href">https://medium.com/media/4fbcf1aaae2f1784e00aabcaa5338922/href</a></iframe><p>This is the final code! A possible use maybe is the more complex multiplier for 2 map function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82f2a84a0e64817b09cb9324c460db3e/href">https://medium.com/media/82f2a84a0e64817b09cb9324c460db3e/href</a></iframe><p>Output:</p><pre>Start emit at 21:21:00.745511Z<br>Emit 0 at 21:21:01.257809Z<br>Emit 1 at 21:21:01.766767Z<br>Emit 2 at 21:21:02.273500Z<br>Emit 3 at 21:21:02.780059Z<br>Emit 4 at 21:21:03.281518Z<br>Collected 0 at 21:21:04.272604Z<br>Collected 2 at 21:21:04.774326Z<br>Collected 4 at 21:21:05.280457Z<br>Collected 6 at 21:21:05.784751Z<br>Collected 8 at 21:21:06.284122Z</pre><p>Thanks, guys. Enjoy it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9735c9dc237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Throttle e Debounce — Uma maneira fácil de otimizar seu código]]></title>
            <link>https://medium.com/@josehhbraz/throttle-e-debounce-uma-maneira-f%C3%A1cil-de-otimizar-seu-c%C3%B3digo-f1c2775a0b42?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c2775a0b42</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[throttling]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 23:01:35 GMT</pubDate>
            <atom:updated>2022-07-13T23:02:56.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debounce e Throttle — Uma maneira fácil de otimizar seu código</h3><h4>Evite processamentos desnecessários e melhore o desempenho da sua aplicação</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NjYqVdWzRrafClDg" /><figcaption>Foto: <a href="https://unsplash.com/@knl_photo?utm_source=medium&amp;utm_medium=referral">Kirsten LaChance</a> | <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Muitas vezes algum evento que não controlamos dispara uma função relativamente custosa. Quando essa função é responsável por atualizar um componente de tela, por exemplo, podemos evitar as execuções repetidas em um intervalo de tempo. Com isso, conseguimos ter melhor desempenho e economizar recursos como energia e processamento.</p><h4>Debounce</h4><p>Nesse contexto, surgem o Throttle e o Debounce, ambos parecidos mas com algumas diferenças. Começando pelo Debounce, ele é responsável por adiar execuções de uma função até que se atinja um tempo sem chamadas à esta função.</p><p>Um exemplo clássico de Debounce são as sugestões de pesquisa do Google. Enquanto o usuário está digitando uma palavra rapidamente não são mostradas novas sugestões. Novos resultados só aparecerão quando o usuário parar um pouco de digitar, digamos por uns 300ms.</p><p>Uma implementação de Kotlin (JVM) poderia ser assim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a4e37005b98f7f1159aa77910e99513/href">https://medium.com/media/9a4e37005b98f7f1159aa77910e99513/href</a></iframe><h4>Throttle</h4><p>Nosso outro personagem de hoje é o Throttle. Podemos vê-lo como uma extensão do Debounce, com uma restrição a mais: ele limita as execuções de uma função para um determinado período de tempo. Caso a função chamada já tenha sido executada no intervalo atual, o Throttle agenda uma execução para depois (como o Debounce). Muitas vezes essa execução agendada pode ser cancelada quando for possível a execução pelo Throttle.</p><p>O Throttle pode ser usado em funções custosas que computam valores apenas para atualizar a tela. Por exemplo em um aplicativo de cotações da bolsa de valores, nenhum usuário reclamará se os valores atualizarem a cada 100ms, por exemplo, se o aplicativo for rápido durante interação.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0edf1e0d9931a1ddc4cf49a8d2a0d3/href">https://medium.com/media/7e0edf1e0d9931a1ddc4cf49a8d2a0d3/href</a></iframe><p>Para ficar mais claro a diferença dos dois componentes, preparei uma imagem simples. Cada | significa uma chamada à função em três casos possíveis: Chamada regular (sem throttle nem debounce), com throttle ou com debounce:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*-vV6vwMKIy0xvq87by9Trg.png" /></figure><p>Uma implementação mais completa (com testes e multiplataforma) pode ser obtida na biblioteca que estou preparando:</p><p><a href="https://github.com/josebraz/kotlin-concurrent-ext">GitHub - josebraz/kotlin-concurrent-ext</a></p><p>Fique a vontade para deixar um comentário abaixo e não esqueça das palminhas se gostou. Até a próxima!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c2775a0b42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como transformar funcionalidades em plugins]]></title>
            <link>https://medium.com/@josehhbraz/como-transformar-funcionalidades-em-plugins-1c0150a4a55f?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c0150a4a55f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programação]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 21:28:51 GMT</pubDate>
            <atom:updated>2022-06-15T21:28:51.217Z</atom:updated>
            <content:encoded><![CDATA[<h4>Diminua o tempo de build, separe responsabilidades e tenha um código mais fácil de manter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L9-mQTGZP-gQkqy1" /><figcaption>Photo by <a href="https://unsplash.com/@thevictorbarrios?utm_source=medium&amp;utm_medium=referral">Victor Barrios</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Neste artigo, você vai aprender uma forma de separar as funcionalidades do seu aplicativo em módulos organizados como plugins. Quando as features são módulos, o tempo de build é significativamente menor e diminui o acoplamento.</p><p>A ideia aqui é que esses módulos podem ser vistos como plugins para o aplicativo final, de forma que ele não dependa de feature alguma para compilar (e funcionar).</p><p>Vamos focar a implementação no desenvolvimento Android com Kotlin e Gradle, mas as ideias podem servir para qualquer framework e linguagens orientadas a objetos.</p><h4>Entendendo plugins</h4><p>Imagine se toda vez que você precisasse programar em uma nova linguagem fosse necessário instalar um editor de textos expecífico. Isso com certeza não é prático. Hoje o que temos são editores, como o <a href="https://code.visualstudio.com/">VS Code</a> e <a href="https://atom.io/">Atom</a>, que suportam plugins para as mais variadas linguagens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qVTih8FQyc08lDMw" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vamos tentar entender (hipoteticamente) como a abordagem de plugin funciona para esses editores de texto. Precisamos ter um contrato combinado entre o editor e os plugins e, assim, garantir uma forma de comunicação. Uma possibilidade seria ter um contrato como este:</p><pre>interface LanguageContract {<br>    fun getReservedWords(): List&lt;String&gt;<br>    fun getIdentifierRegex(): Regex<br>    fun tryProcess(inputFile: File): LanguageProcessResult<br>}</pre><p>Criamos uma interface <em>LanguageContract</em> que vai expor todas as funções que o nosso editor precisa para funcionar corretamente para uma determinada linguagem.</p><ul><li><strong><em>getReservedWords()</em></strong>: Precisamos da lista de palavras reservadas para dar highlight;</li><li><strong><em>getIdentifierRegex()</em></strong>: Saber como é definido um identificador na linguagem (nome de função, variável, etc) para a análise léxica;</li><li><strong><em>tryProcess(inputFile)</em></strong>: Fazer um processo de análise completa de uma entrada, retornando o resultado em um formato conhecido, como no código abaixo.</li></ul><pre>interface LanguageProcessResult {<br>    fun getErrorsList(): List&lt;LanguageProcessResultItem&gt;<br>    fun getWarningList(): List&lt;LanguageProcessResultItem&gt;<br>}<br><br>interface LanguageProcessResultItem {<br>    fun getTitle(): String<br>    fun getMessage(): String<br>    fun getLine(): Int<br>    fun getColumn(): Int<br>    fun getFixActions(): List&lt;String&gt;<br>}</pre><p>O editor pode chamar o método <em>tryProcess</em> passando o arquivo que está sendo editado e, depois disso, mostrando as mensagens de erro e warning — se existirem.</p><p>Internamente, o plugin vai chamar os analisadores (léxico, sintático e semântico) da linguagem e vai criar o resultado no formato esperado pelo editor (<em>LanguageProcessResult</em>).</p><p>Notem que nessa abordagem o editor não precisa ter o compilador da linguagem editada, tudo fica a cargo do plugin que é específico para cada linguagem.</p><p>No caso de uma nova versão em que o editor suporte mostrar documentação de métodos, é só adicionar uma nova função na interface <em>LanguageContract</em> que recebe o nome do método e retorna a documentação.</p><h4>Features como plugins</h4><p>Seguindo a ideia do caso do editor de texto, podemos imaginar que todas as features seguem o mesmo “contrato”. A complexidade deste contrato vai ser proporcional à complexidade do aplicativo.</p><p>Por exemplo, se o aplicativo tem um <a href="https://material.io/components/navigation-drawer">menu burguer</a> para acessar as funcionalidades, cada feature que se “pluga” precisa dizer como quer aparecer nesse menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*al2uMLF7B54q5fGS" /><figcaption>Imagem: <a href="https://material.io/components/navigation-drawer">Material Design</a>/Reprodução</figcaption></figure><pre>interface FeatureContract {<br>    val featureMenuBurger: FeatureMenuBurger?<br>}<br><br>data class FeatureMenuBurger(<br>    @DrawableRes val iconId: Int,<br>    @StringRes val titleId: Int,<br>    val activity: Class&lt;out AppCompatActivity&gt;,<br>    val priority: Int = PRIORITY_LOWER<br>) {<br>    companion object {<br>        const val PRIORITY_HIGHER: Int = Int.MIN_VALUE<br>        const val PRIORITY_LOWER: Int = Int.MAX_VALUE<br>    }<br>}</pre><p>O <em>FeatureContract</em> tem um campo f<em>eatureMenuBurger</em> que diz exatamente como mostrar a opção da funcionalidade no menu burguer (ícone, título, activity que deve abrir e prioridade). Se o campo for nulo, significa que a funcionalidade não vai aparecer no menu.</p><p>Cada feature pode ser um módulo separado que depois irá se “registrar” como feature no aplicativo em tempo de execução. Para isso, precisamos trocar dados da feature com o aplicativo host (aplicação base).</p><p>Essa troca precisa ser feita de modo genérico, por interface, para que as features também possam ser reaproveitadas em outros aplicativos.</p><pre>interface AppHostContract {<br>    fun addFeature(featureContract: FeatureContract)<br>    fun removeFeature(featureContract: FeatureContract)<br>    fun getFeatures(): List&lt;FeatureContract&gt;<br>    fun getApplicationName(): String<br>}</pre><p>O <em>AppHostContract </em>modela quais operações um aplicativo host precisa suportar. Basicamente, temos os métodos de adição, remoção e listagem das features em tempo de execução. Além disso, temos um método que retorna o nome da aplicação.</p><p>Essa interface precisa ser implementada pelo nosso Application (do Android), mais ou menos dessa forma:</p><pre>class MyApplication: Application(), AppHostContract {<br><br>    private val features = <em>mutableListOf</em>&lt;FeatureContract&gt;()<br><br>    override fun addFeature(featureContract: FeatureContract) {<br>        features.add(featureContract)<br>    }<br><br>    override fun removeFeature(featureContract: FeatureContract) {<br>        features.remove(featureContract)<br>    }<br><br>    override fun getFeatures(): List&lt;FeatureContract&gt; = features<br><br>    override fun getApplicationName(): String = &quot;Test App&quot;<br>}</pre><h4>Se plugando no aplicativo (apenas Android)</h4><p>Beleza! Mas como uma feature se registra no aplicativo? Podemos usar uma biblioteca que se chama <a href="https://developer.android.com/topic/libraries/app-startup">App Startup</a>. Ela nos proporciona uma forma de executar código quando o aplicativo abre e, com isso, podemos notificar o aplicativo que ela — a feature em questão — existe.</p><p>De acordo com a documentação da biblioteca Startup, podemos estender um <em>Initializer</em> que tem o método <em>create</em> e recebe um <em>context:</em></p><pre>class FeatureExampleInitialize : Initializer&lt;FeatureContract&gt; {<br><br>    override fun create(context: Context): FeatureContract {<br>        <em>TODO</em>()<br>    }<br><br>    override fun dependencies() = <em>emptyList</em>()<br>}</pre><p>Esse context recebido é o nosso MyApplication! Temos certeza que ele estende o <em>AppHostContract, </em>e é com isso que conseguimos nos registrar.</p><pre>override fun create(context: Context): FeatureContract {<br>    return FeatureExampleContract().<em>also </em><strong>{<br>        </strong>(context as AppHostContract).addFeature(<strong>it</strong>)<br>    <strong>}<br></strong>}</pre><p>Sempre que o aplicativo é aberto, todas as features se plugam no aplicativo e ele sabe que elas existem verificando a lista de <em>features</em> no application.</p><h4>Tudo junto em um projeto Android</h4><p>Agora vamos juntar todo o nosso conhecimento desse artigo em um projeto de fato! O Projeto está <a href="https://github.com/josebraz/AndroidFeaturePluginExample">disponível aqui</a>, e é apenas um aplicativo com um menu burguer onde é possível acessar as features. Cada feature é uma tela simples com um TextView no centro.</p><p><a href="https://github.com/josebraz/AndroidFeaturePluginExample">GitHub - josebraz/AndroidFeaturePluginExample</a></p><p>Esse projeto contém 2 módulos de features e um módulo <em>base</em>, que é usado por todos os outros módulos e contém as interfaces <a href="https://github.com/josebraz/AndroidFeaturePluginExample/blob/main/base/src/main/java/com/josebraz/myapplication/base/FeatureContract.kt"><em>FeatureContract</em></a> e <a href="https://github.com/josebraz/AndroidFeaturePluginExample/blob/main/base/src/main/java/com/josebraz/myapplication/base/AppHostContract.kt"><em>AppHostContract</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*iGJ89Q3hvJXd4mDuhmPIdw.jpeg" /><figcaption>Imagem: José Braz</figcaption></figure><p>O app possui 3 flavors: <em>full</em>, <em>standard</em> e <em>demo</em>. Apenas o flavor <em>full</em> tem as duas features; o <em>standard</em> tem apenas a <em>feature1; </em>e o <em>demo</em> não tem feature alguma.</p><p>Cada feature suporta aparecer no menu burger (olhem o <a href="https://github.com/josebraz/AndroidFeaturePluginExample/blob/main/features/feature1/src/main/java/com/josebraz/myapplication/feature1/Feature1Contract.kt"><em>Feature1Contract</em></a> e <a href="https://github.com/josebraz/AndroidFeaturePluginExample/blob/main/features/feature2/src/main/java/com/josebraz/myapplication/feature2/Feature2Contract.kt"><em>Feature2Contract</em></a>) com suas configurações específicas.</p><p>O código do menu burguer está no módulo base. Em um determinado momento, ele pega o contexto atual (que é o <em>AppHostContract</em>) e lista todas as features que o host conhece para mostrar no menu:</p><pre>val items = (<em>LocalContext</em>.current as AppHostContract).getFeatures()<br>    .<em>mapNotNull </em><strong>{ it</strong>.featureMenuBurger <strong>}<br>    </strong>.<em>sortedBy </em><strong>{ it</strong>.priority <strong>}</strong></pre><p>Além disso, o projeto apenas compila os módulos necessários para o flavor atual — o que acaba diminuindo muito o tempo para o build ser concluído. Essa lógica está no <a href="https://github.com/josebraz/AndroidFeaturePluginExample/blob/main/app/build.gradle"><em>app/build.gradle</em></a>. É basicamente pegar o flavor atual e eliminar os módulos que não pertencem a ele:</p><pre>final currentFlavor = getCurrentFlavor()<br>final isSync = currentFlavor == &quot;&quot;<br><br>final commonModules = [&quot;:base&quot;]<br>var featureModules = file(&quot;../features&quot;).listFiles()<br>        .collect <strong>{</strong>&quot;:features:$<strong>{</strong>it.name<strong>}</strong>&quot; <strong>}<br><br></strong>if (!isSync) {<br>    if (currentFlavor !in [&quot;standard&quot;, &quot;full&quot;]) {<br>        featureModules -= &quot;:features:feature1&quot;<br>    }<br>    if (currentFlavor !in [&quot;full&quot;]) {<br>        featureModules -= &quot;:features:feature2&quot;<br>    }<br>}<br><br>(commonModules + featureModules).each <strong>{<br>    </strong>if (!isSync) {<br>        println(&quot;Building app with $it...&quot;)<br>    }<br>    implementation project(it)<br><strong>}</strong></pre><h4>Conclusão</h4><p>Transformar suas features em plugin permite maior flexibilidade do projeto, principalmente para projetos com vários flavors que dependem de features diferentes. Com isso, compilamos apenas o que é necessário.</p><p>Obrigado por chegar até aqui! Qualquer dúvida deixe nos comentários e se gostou dá clap aí.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c0150a4a55f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como resolver os problemas de concorrência em coleções com Kotlin]]></title>
            <link>https://medium.com/@josehhbraz/como-resolver-os-problemas-de-concorr%C3%AAncia-em-cole%C3%A7%C3%B5es-com-kotlin-8fa92e21324?source=rss-b06bf557dc4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa92e21324</guid>
            <category><![CDATA[concurrentmodification]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[concorrenciakotlin]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[José Braz]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 00:01:17 GMT</pubDate>
            <atom:updated>2022-06-20T14:16:31.370Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uma comparação entre Monitores e Leitores-Escritores</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_89i0dDIsl0fKkOT" /><figcaption>Photo by <a href="https://unsplash.com/@bradencollum?utm_source=medium&amp;utm_medium=referral">Braden Collum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Em um projeto multithread é comum nos depararmos com problemas de concorrência, principalmente em estruturas de dados como listas e mapas. O famoso <em>ConcurrentModificationException</em> é um erro que acontece normalmente quando uma thread altera uma coleção ao mesmo tempo que uma outra thread esta iterando nessa estrutura.</p><p>Neste artigo quero mostrar algumas possibilidades de como resolver esse problema de forma rápida, mas tenha em mente que o melhor jeito de evitar problemas de concorrência é se preocupando com eles a nível do projeto e arquitetura do software.</p><h3>Solução usando o padrão Monitor</h3><p>Um <a href="https://en.wikipedia.org/wiki/Monitor_(synchronization)">monitor</a> no Kotlin é basicamente uma classe que disponibiliza métodos seguros para serem acessado por mais de uma thread, garantindo que não haverá problemas de concorrência. A solução usando monitores é simples de implementar, consiste em encapsular a coleção e adicionar as funções desejadas.</p><pre>class SynchronizedList&lt;T&gt;(<br>    initialList: MutableList&lt;T&gt;? = null<br>) {<br>    // soft copy received list or create a new empty list<br>    private val _resource = initialList?.<em>toMutableList</em>() ?: <em>mutableListOf</em>()<br>    <br>    private val _lock = Any()<br>    <br>    operator fun get(index: Int): T {<br>        return <em>synchronized</em>(_lock) <strong>{ </strong>_resource[index] <strong>}<br>    }</strong></pre><pre><strong>    </strong>operator fun set(index: Int, element: T): T {<br>        return <em>synchronized</em>(_lock) <strong>{ </strong>_resource.set(index, element) <strong>}<br>    </strong>}<br><br>    fun add(element: T): Boolean {<br>        return <em>synchronized</em>(_lock) <strong>{ </strong>_resource.add(element) <strong>}<br>    </strong>}<br><br>    fun remove(element: T): Boolean {<br>        return <em>synchronized</em>(_lock) <strong>{ </strong>_resource.remove(element) <strong>}<br>    </strong>}<br>    <br>    fun clear() = <em>synchronized</em>(_lock) <strong>{ </strong>_resource.clear() <strong>}</strong></pre><pre>    .....<br>}</pre><p>Todo o método criado no Monitor precisa ser protegido com o bloco <em>synchronized</em> passando um objeto para ser o lock. Nessa implementação não queremos que nenhum método seja acessado por duas threads ao mesmo tempo, por isso precisamos usar sempre o mesmo lock.</p><p>Por construção, essa solução tem vários problemas. O principal é que não é possível fazer leituras simultâneas na lista, pois apenas uma thread pode acessar o recurso ao mesmo tempo. Além disso:</p><ul><li>Não é multiplataforma, uma vez que usa a função <em>synchronized</em> do Java</li><li>Bloqueia a thread até que ela ganhe o acesso à seção crítica</li><li>É fechada para extensões, visto que precisa manter o recurso e o lock privados</li><li>Possibilidade de deadlocks</li></ul><p>Dá pra fazer melhor? Sim! estamos usando Kotlin e temos o poder das corrotinas ao nosso lado.</p><h3>Solução usando Leitores-Escritores</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfY7g1mIOBfvU5rQ" /><figcaption>Photo by <a href="https://unsplash.com/@craftedbygc?utm_source=medium&amp;utm_medium=referral">Green Chameleon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine várias pessoas ao redor de uma folha de papel, alternando entre escrever e ler o que foi escrito. O problema <a href="https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem">Leitores-Escritores</a> é a necessidade de controlar o acesso ao papel, de forma que haja apenas um escritor OU apenas (inúmeros) leitores por vez.</p><blockquote>Leituras concorrentes podem ser feitas simultaneamente sem problema algum, uma vez que elas não alteram os dados.</blockquote><p>Podemos usar a mesma ideia da solução do problema dos Leitores-Escrit ores, mas aplicar a uma coleção, ao invés de um papel. Segue uma implementação genérica para o acesso de leitura concorrente simultânea e escrita única:</p><pre>import kotlinx.coroutines.sync.Mutex<br>import kotlinx.coroutines.sync.withLock<br><br>open class ManyReadersOneWriter&lt;WT: RT, RT&gt;(<br>    private val resource: WT<br>) {<br><br>    private var readCount = 0<br>    private val readMutex = <em>Mutex</em>()<br>    private val resourceMutex = <em>Mutex</em>()<br>    private val serviceQueue = <em>Mutex</em>()<br><br>    suspend fun &lt;R&gt; writer(block: suspend (WT) -&gt; R): R {<br>        try {<br>            serviceQueue.withLock <strong>{<br>                </strong>resourceMutex.lock()<br>            <strong>}<br>            </strong>return block.invoke(resource)<br>        } finally {<br>            resourceMutex.unlock()<br>        }<br>    }<br><br>    suspend fun &lt;R&gt; reader(block: suspend (RT) -&gt; R): R {<br>        try {<br>            serviceQueue.withLock <strong>{<br>                </strong>readMutex.withLock <strong>{<br>                    </strong>readCount += 1<br>                    if (readCount == 1) {<br>                        resourceMutex.lock()<br>                    }<br>                <strong>}<br>            }<br>            </strong>return block.invoke(resource)<br>        } finally {<br>            readMutex.withLock <strong>{<br>                </strong>readCount -= 1<br>                if (readCount == 0) {<br>                    resourceMutex.unlock()<br>                }<br>            <strong>}<br>        </strong>}<br>    }<br>}</pre><p>Nessa implementação temos duas primitivas:</p><ul><li><em>writer</em>: Quando um escritor quer acessar o recurso, ele entra em uma fila (tentando pegar o lock do <em>serviceQueue</em>) e efetua o lock do recurso (<em>resourceMutex.lock()</em>). Neste momento ele pode acessar o recurso com a garantia de que não haverá ninguém lendo ou escrevendo.</li><li><em>reader</em>: Podemos ter vários leitores ao mesmo tempo. Isso é atingido com um contador de leitores atuais (<em>readCount</em>) que, quando passa a valer 1, obtém o lock e só larga quando o contador chegar em 0. O <em>readMutex</em> protege a variável <em>readCount</em> para que essas operações de comparação e set sejam vistas como atômicas.</li></ul><p>Note que o tipo genérico WT (<em>write type</em>) é uma extensão do RT (<em>read type</em>). Os métodos <em>reader</em> e <em>writes</em> são <em>suspend</em>, devido ao uso do Mutex e por isso são bem mas inteligentes que uma função bloqueante, como no caso do Monitor.</p><h4>Aplicando às coleções</h4><p>Agora vamos aplicar o <em>ManyReadersOneWriter</em> em algumas coleções e mostrar como podemos brincar com o uso das interfaces mutáveis e imutáveis delas:</p><pre>class ConcurrentList&lt;T&gt;(<br>    initialList: MutableList&lt;T&gt;? = null<br>): ManyReadersOneWriter&lt;MutableList&lt;T&gt;, List&lt;T&gt;&gt;(<br>    initialList?.<em>toMutableList</em>() ?: <em>mutableListOf</em>()<br>)</pre><pre>class ConcurrentMap&lt;K, T&gt;(<br>    initialMap: MutableMap&lt;K, T&gt;? = null<br>): ManyReadersOneWriter&lt;MutableMap&lt;K, T&gt;, Map&lt;K, T&gt;&gt;(<br>    initialMap?.<em>toMutableMap</em>() ?: <em>mutableMapOf</em>()<br>)</pre><pre>class ConcurrentSet&lt;T&gt;(<br>    initialSet: MutableSet&lt;T&gt;? = null<br>): ManyReadersOneWriter&lt;MutableSet&lt;T&gt;, Set&lt;T&gt;&gt;(<br>    initialSet?.<em>toMutableSet</em>() ?: <em>mutableSetOf</em>()<br>)</pre><p>Essas implementações são seguras em relação às coleções. Quando o método <em>reader</em> ganha acesso ao recurso, o leitor só recebe a interface imutável da coleção. No caso do <em>writer</em> é o contrário, o escritor recebe a interface mutável da coleção.</p><p>Estamos livres para adicionar quantos métodos forem necessários para nossa estrutura. Isso facilita a leitura do código e não precisamos usar diretamente as primitivas <em>reader</em> e <em>writer</em> da classe base <em>ManyReadersOneWriter.</em></p><pre>suspend inline fun &lt;T&gt; ConcurrentList&lt;T&gt;.set(<br>    index: Int, element: T<br>): T = writer <strong>{ it</strong>.set(index, element) <strong>}<br><br></strong>suspend inline fun &lt;T&gt; ConcurrentList&lt;T&gt;.add(<br>    element: T<br>) = writer <strong>{ it</strong>.add(element) <strong>}</strong></pre><pre>suspend inline fun &lt;T&gt; ConcurrentList&lt;T&gt;.get(index: Int): T {<br>    return reader <strong>{ it</strong>[index] <strong>}<br></strong>}<br><br>suspend inline fun &lt;T&gt; ConcurrentList&lt;T&gt;.filter(<br>    crossinline predicate: (T) -&gt; Boolean<br>): List&lt;T&gt; = reader <strong>{ </strong>resource <strong>-&gt;<br>    </strong>resource.<em>filter</em>(predicate)<br><strong>}<br><br></strong>suspend inline fun &lt;T&gt; ConcurrentList&lt;T&gt;.forEach(<br>    crossinline action: (T) -&gt; Unit<br>) = reader <strong>{ </strong>resource <strong>-&gt;<br>    </strong>resource.<em>forEach</em>(action)<br><strong>}</strong></pre><h4>Ainda temos deadlocks?</h4><p>Essa solução não tem os problemas da solução com Monitores, mas ainda pode causar deadlocks em alguns casos específicos. Se em algum momento o programador chamar as primitivas de <em>writer</em> e/ou <em>reader </em>dentro de um bloco <em>writer</em>, como no exemplo:</p><pre>val concurrentList = ConcurrentList&lt;Int&gt;()<br>concurrentList.writer <strong>{<br>    </strong>concurrentList.reader <strong>{<br>        </strong><em>println</em>(<strong>it</strong>)<strong><br>    }<br>}</strong></pre><p>Ou <em>writer</em> dentro de um bloco <em>reader</em>:</p><pre>val concurrentList = ConcurrentList&lt;Int&gt;()<br>concurrentList.reader <strong>{<br>    </strong>concurrentList.writer <strong>{<br>        </strong><em>println</em>(<strong>it</strong>)<strong><br>    }<br>}</strong></pre><p>Mas o deadlock não acontece com duas ou mais leituras encadeadas, porque podemos ter múltiplos leitores ao mesmo tempo.</p><pre>val concurrentList = ConcurrentList&lt;Int&gt;()<br>concurrentList.reader <strong>{<br>    </strong>concurrentList.reader <strong>{<br>        </strong><em>println</em>(<strong>it</strong>)<br>    <strong>}<br>}</strong></pre><h3>Conclusão</h3><p>Nada envolvendo programação é uma bala de prata. Use essas soluções para concorrência em estruturas com sabedoria, pois elas adicionam um overhead no seu projeto e o ideal seria organizá-lo de forma a limitar a necessidade de uso de soluções usando locks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZfiHW5e1Yt1RaIto" /><figcaption>Photo by <a href="https://unsplash.com/@liaphotography?utm_source=medium&amp;utm_medium=referral">Lia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa92e21324" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>