<?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 Kunal Sale on Medium]]></title>
        <description><![CDATA[Stories by Kunal Sale on Medium]]></description>
        <link>https://medium.com/@kunal-sale92?source=rss-70814551ef3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1hQiiClM41S1jPA-D0t9_g.jpeg</url>
            <title>Stories by Kunal Sale on Medium</title>
            <link>https://medium.com/@kunal-sale92?source=rss-70814551ef3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:33:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunal-sale92/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[Unshared parts of SharedFlow — Kotlin]]></title>
            <link>https://kunal-sale92.medium.com/unshared-parts-of-sharedflow-kotlin-21a471a65075?source=rss-70814551ef3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a471a65075</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Kunal Sale]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 17:17:29 GMT</pubDate>
            <atom:updated>2022-03-01T18:12:31.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unshared parts of SharedFlow — Kotlin coroutine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-xfKK8gyr1X0wwSeUgXuA.jpeg" /><figcaption>Credit: <a href="https://unsplash.com/photos/6ArTTluciuA">https://unsplash.com/photos/6ArTTluciuA</a></figcaption></figure><p>Kotlin coroutine has made concurrency look easy to the developers. It has provided several APIs in kotlinx.coroutines and kotlinx.coroutines.flow . SharedFlow is one such API which is used to concurrently handle the stream of data. Most commonly used SharedFlows are MutableSharedFlow and MutableStateFlow (special type of MutableSharedFlow). Let’s discuss about the MutableSharedFlow to demonstrate the working of SharedFlow, as MutableStateFlow is self understood, once the former is clear.</p><h4>Introduction to SharedFlow</h4><p>SharedFlow are hot flows and same flow can be shared amongst multiple subscribers. It remains in the memory forever, even though they are not subscribed by any subscribers, and hence it is called hot flow. Its subscribers will not behave in a same way, and they are cancelleable. Generally, subscribers will be listening to the flow in a coroutine scope, which is independent, and hence once the coroutine scope is cancelled, subscriber will also get unsubscribed.</p><blockquote>It is safe to collect flow from viewModelScope and lifecycleScope, as they are maintained by system and hence they get destroyed accordingly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*W1h6RJCD4ryJHRBh51_5LQ.png" /><figcaption>SharedFlow pushing data to multiple subscribers</figcaption></figure><blockquote><strong>Note:</strong> Kotlin also supports cold flow through <em>flow { }</em>, which doesn’t executes until the some subscribers collects it. Every subscribers gets its own flow and doesn’t share anything.</blockquote><p>Let’s see how to initialize it, and below is the best practice to follow:</p><pre>private val<strong> </strong>_sharedFlow = MutableSharedFlow&lt;Int&gt;()<br>val<strong> </strong>sharedFlow = _sharedFlow.asSharedFlow()</pre><p><strong>Code walkthough:</strong></p><ol><li>_sharedFlow is a private MutableSharedFlow , it prohibits outside code to mutate the state, and only the enclosing class to mutate it.</li><li>sharedFlow is a read-only shared flow, which is public and accessible to subscribers to listen to the flow.</li><li>_sharedFlow.asSharedFlow() is assigned to sharedFlow. asSharedFlow is absolutely necessary as it returns instance of ReadonlySharedFlow , and hence no one can cast the flow to any other subclass and mutate it.</li><li>MutableSharedFlow&lt;Int&gt;()is not a constructor, it is a function used to initialize the implementation class.</li></ol><p>Let’s take a closer look at MutableSharedFlow&lt;T&gt;()<em> </em>and it’s parameters.</p><pre>public fun<strong> </strong>&lt;T&gt; MutableSharedFlow(<br>    <strong>replay: Int = 0</strong>,<br>    <strong>extraBufferCapacity: Int = 0</strong>,<br>    <strong>onBufferOverflow: BufferOverflow = BufferOverflow.<em>SUSPEND</em></strong><em><br></em>): MutableSharedFlow&lt;T&gt;</pre><p>MutableSharedFlow has 3 parameters and there are default values for it. They have their own significance and the SharedFlow behaviour changes accordingly. There are 2 methods for emitting the value to the subscribers, emit() and tryEmit() .</p><p>emit() — It is a suspending function and it suspends the execution until all the subscribers collects the emission. <em>There are situations where it will not suspend the execution.</em></p><p>tryEmit() — It is a non-suspending function<strong>,</strong> which can be used to emit the values from non-suspending function as well. It will try to emit the value immediately. (in detail explanation in the below section)</p><p>Let’s take a help of a story to understand the above parameters and functions.</p><h4><strong>Story time: </strong>🐢 vs 🐇</h4><p>Once upon a time there was a race between Tortoise and Hare, and the one who will reach the finish line first wins the race. <strong>Race begins!!!</strong> Tortoise starts the race immediately, and Hare being lazy starts 5 secs later. Timer is ticking every second and both of them are moving ahead at their own pace. Tortoise needs 5 seconds to complete 1 meter and Hare takes 1 second to complete that same distance. Hare quickly crosses tortoise, and looks like he will win the race. Guess who will win the race in the end.</p><p>Even if the race is thrilling, we are not really interested in the winner. This scenario can help us understand many aspects of the SharedFlow.</p><p>Let’s make the timer as SharedFlow, which is emitting the time elapsed at every second. To mock tortoise slowness, we have added delay of 5 seconds immediately after collecting the emission from timer. Hare is fast subscriber, who collects emissions and there are no delays. Fast subscriber has subscribed late by 5secs, and hence it has missed 5 emissions from the SharedFlow.</p><p>Refer this code where actually a race is happening. You can copy the code and run. It will show you the winner in the end. Don’t run on kotlin playground as the code takes longer time to execute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa17d321c6b882ce6d04a4864373f1ba/href">https://medium.com/media/aa17d321c6b882ce6d04a4864373f1ba/href</a></iframe><h4>Replay the emissions 🔁</h4><p>In our example, fast subscriber aka Hare, subscribes the flow after 5 secs, so it has missed 5 previous emissions. There can be a use case where we want the previous emission to be received by the new subscriber. We can achieve this by setting the <strong>replay </strong>parameter to the number of emission required to be re-emitted to the new subscriber. SharedFlow<em> </em>maintains a list of<em> </em>previously-emitted items<em> </em>in a <strong>replayCache </strong>variable<strong>, </strong>which stores the previous emissions of size replay. Replay happens in a non-suspending fashion and subscriber immediately receives the values.</p><p>Hence, by setting the replay to 5 for our example, fast subscriber will get all the previous emissions first and then it will continue to get the ongoing ones.</p><h4>What if the replayCache is full and a new value has to be emitted?</h4><p>Fast subscriber is always available and slow subscriber takes the value at an interval of 5 secs. SharedFlow keeps a track of the index of value being collected by the slowest and fastest subscriber respectively. Hence, SharedFlow will keep the value in the buffer until the slowest subscriber has not collected the oldest value, in the replayCache it will be at the index 0.</p><p>Suppose buffer is full with the values and slowest subscriber has not yet resumed to collect the oldest value. Meanwhile a new value arrives and is ready to be emitted, unfortunately the buffer is full. What will happen in such cases? Also, emit() and tryEmit() will behave differently depending on the option.</p><p>SharedFlow has given 3 options to deal with such situations. Let’s take a look.</p><p><strong>BufferOverflow.<em>SUSPEND</em></strong> — This is the default option provided. If the above situation happens and SUSPEND is used, execution will be suspended until the oldest value is collected and there is space in the buffer for the new value. Although, it will happen only if emit() is used for the emission, as it is suspending. If tryEmit() is used, then the new data will be lost and function will return false, which means it tried to emit the data but it couldn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acIplLsG-L4H3iOLDTAJXw.png" /><figcaption>BufferOverflow.<em>SUSPEND</em></figcaption></figure><p><strong>Note:</strong> Be careful while using the tryEmit() in case of SUSPEND, as we saw there will be data lost.</p><p><strong>BufferOverflow.<em>DROP_OLDEST</em></strong><em> — </em>This option can be used if we are interested in the latest data and older data can be ignored. It says whenever the buffer is full, then I will remove the oldest value from the buffer and make room for the latest value. This option always guarantees to emit value immediately to the subscriber who is ready to collect it. emit() and tryEmit() will behave in same way and both will be non-suspending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCA6dBmbp_m9-zOhsmT1hQ.png" /><figcaption>BufferOverflow.<em>DROP_OLDEST</em></figcaption></figure><p><strong>Note:</strong> The slow subscriber will lose the old data, as it might get removed when the subscriber was performing something else and not able to collect it.</p><p><strong>BufferOverflow.<em>DROP_LATEST</em></strong><em> — </em>It will drop the new value and replayCache will be same, as it is dropping the latest value. emit() and tryEmit() will have same effect if the buffer is full, it will ignore the emission. In this option, due to slow processing of the subscriber, there can be loss of the latest data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*fMNmT25fF-wBo0KqlgD_iA.png" /><figcaption>BufferOverflow.<em>DROP_LATEST</em></figcaption></figure><blockquote>DROP_LATEST and DROP_OLDEST are only applicable, if the replay or extraBufferCapacity is greater than 0, passing nothing or 0 will throw an IllegalArgument exception.</blockquote><h4>Quick tour to StateFlow:</h4><ol><li>StateFlow shares only one value; a current value</li><li>It replays the state to the subscriber, even if subscribers joins later.</li><li>It needs initial value.</li><li>It emits value only when the state changes.</li><li>It inherits SharedFlow, hence previously mentioned that it is special type of SharedFlow.</li></ol><p>Same can be achieved with MutableSharedFlow as well, refer below code:</p><pre>val<strong> </strong><em>sharedFlow </em>= <em>MutableSharedFlow</em>&lt;Int&gt;(<br>    replay = 1,<br>    onBufferOverflow = BufferOverflow.<em>DROP_OLDEST<br></em>)<br>sharedFlow.tryEmit(initialValue)<br>val<strong> </strong><em>stateFlow </em>= <em>sharedFlow</em>.<em>distinctUntilChanged</em>()</pre><h4>Summary:</h4><ol><li>SharedFlow are hot flow 🔥.</li><li>It can be used to create Event bus like service, where values needs to be broadcast to multiple subscribers.</li><li>MutableSharedFlow and MutableStateFlow are most commonly used SharedFlow.</li><li>SharedFlow can replay previous data to the new subscribers.</li><li>There are three OnBufferFlowStrategy to handle if the buffer is full.</li></ol><p><em>I hope you enjoyed the story and found this article useful. Also, Tortoise slowly and steadily wins the race in the end, Hare sleeps just before the finish line.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a471a65075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Espresso, Please…]]></title>
            <link>https://kunal-sale92.medium.com/one-espresso-please-3e9cf0804f8c?source=rss-70814551ef3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9cf0804f8c</guid>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[instrumentation-testing]]></category>
            <category><![CDATA[espresso-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Kunal Sale]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 04:36:56 GMT</pubDate>
            <atom:updated>2021-09-14T04:45:34.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>One Espresso Please…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_cnOfVw43FmVeQhM4l7EA.png" /></figure><p>Test cases are fun to write which I discovered recently. A few days back, I felt that let’s start writing UI test cases for new development work using Espresso framework and experience the benefits of using it. Getting started with writing test cases is a bit difficult but, once it hits you, then it is easy and becomes a habit. I find it helpful and will share one immediate benefit, later in the article, which I experienced by writing the test cases and after that, I said to myself, <em>“One Espresso, Please!”</em></p><p>In this article, I will cover basics of UI testing and Espresso library in Android which is used to do UI test.</p><p>First, Let&#39;s analyze how a user interacts with an app.</p><ol><li>Opens the app.</li><li>Locate some UI or views.</li><li>Acts</li><li>Waits for the result and sees the changes accordingly in the UI.</li></ol><p>I usually perform the same steps manually to test the app in the development phase. I’m sure most of you might be doing the same as well, but this time instead of performing it manually, I did automated UI testing.</p><p>Automated UI testing falls under Instrumentation testing as it requires a physical device or Emulator to perform the testing. Unlike unit test, it doesn’t run in the JVM environment, but it needs to run in the same process as the app. Let’s take a look at the Espresso library now.</p><p>In Android, we have Espresso framework which is widely used for the UI testing. It provides the APIs to simulate the user interactions within the single target app. Espresso runs the test cases when the main thread is idle so it provides synchronization with the UI.</p><p><strong>Basic ingredients of Espresso:</strong></p><p><strong>ViewInteraction:</strong></p><ul><li>It provides an interface to interact with the view such as to perform a task or assert the value.</li><li>It takes the ViewMatcher object to search for a view in a hierarchy.</li><li>View has to be part of the hierarchy else exception will be thrown.</li></ul><p><strong>ViewMatcher:</strong></p><ul><li>It defines different criteria for the view which is to be searched.</li><li>If there are views with common properties like resource id’s, etc, then we need to provide multiple ViewMatchers to search a View.</li></ul><p><strong>ViewActions:</strong></p><ul><li>Once the view is found we can perform any action on it. In order to perform any actions, Espresso provides ViewAction.</li></ul><p><strong>ViewAssertion:</strong></p><ul><li>ViewAssertions provide collections to assert the result of any action or view.</li></ul><p>Concepts are better understood when we actually try it out. Let’s take a trivial screen like below where there are 3 views:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOD_D0OJ5-szxiHDdTr7dA.jpeg" /><figcaption>1. Two Image buttons with + and — signs and one TextView.</figcaption></figure><p>Use cases:</p><ol><li>Initially the TextView value is set to 0.</li><li>When user clicks on + sign button, increment the value by 1 and set it to the TextView.</li><li>When the user clicks on the minus sign button before, doing anything else, then it should not decrement the counter to a negative value.</li><li>When the user clicks on the minus sign button for the first time then it should not decrement the value to -1.</li><li><strong>Initially the TextView (@+id/tvCounter) value is set to 0.</strong></li></ol><ul><li>Here we are checking whether tvCounter is displayed and initially the value of the counter is 0.</li><li>On the first line, we get the view by passing the id to the ViewMatcher <strong>withId(R.id.<em>tvCounter</em>) </strong>and pass the ViewMatcher to<strong> onView(ViewMatcher).</strong></li><li>Once we have the view then we can check the above conditions, whether it is displayed and the text is 0.</li><li>In order to do it, we will use <strong>check(ViewAssertion), </strong>a ViewIteraction in which we pass<strong> </strong>ViewAssertion<strong> matches(ViewMatchers).</strong></li><li>Now there are two conditions to check hence to check the result collectively, <strong>allOf() </strong>is used and it takes ViewMatchers and passes the test only if all the conditions are true.</li></ul><pre>@Test<br><strong>fun </strong>checkIfTextViewIsDisplayedWithZeroCount() {<br>    onView(withId(R.id.<em>tvCounter</em>))<br>        .check(matches(allOf(isDisplayed(), withText(<strong>&quot;0&quot;</strong>))))<br>}</pre><p><strong>2. When user clicks on + sign button(@+id/ibIncrement), increment the value by 1 and set it to the TextView.</strong></p><pre>@Test<br><strong>fun </strong>checkIfValueIsIncrementedOnIncrementButtonClicked() {<br>    onView(withId(R.id.<em>ibIncrement</em>))<br>        .perform(click())<br>    onView(withId(R.id.<em>tvCounter</em>))<br>        .check(matches(withText(<strong>&quot;1&quot;</strong>)))<br>}</pre><ul><li>Great, the first test case was simple but still has a lot of components of Espresso being used in it.</li><li>In this test case, we need to perform an action on the view and check the result.</li><li>To perform any action Espresso provides a class called <strong>ViewActions</strong> and can be used to perform various actions like click, double click, typeText, etc.</li><li>We need <strong>click()</strong> action to perform the click on the increment button.</li><li>Whenever there is a need for interaction to be done on a view, then we need to use ViewInteraction. Previously we saw onView(), check() for the first test and now we will use <strong>perform().</strong></li><li>perform() takes an action as argument and that is click() for this test case.</li><li>In the first statement, we got the ImageButton and then performed an action click on it.</li><li>Now we need to validate the result and for which we need to check whether “1” is set to the tvCounter or not.</li><li>Code for this is similar to the first test case and just we need to replace “0&quot; with “1&quot;.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*LrU2ttWPcNLBKPzLNt8CXg.png" /><figcaption>Created on <a href="https://app.diagrams.net/">https://app.diagrams.net</a>. Diagram to visualise the above test case.</figcaption></figure><p><strong>3. When user clicks on minus sign button(@+id/ibDecrement), decrement the value by 1 and set it to the TextView.</strong></p><pre>@Test<br><strong>fun </strong>checkIfValueIsDecrementedOnDecrementButtonClicked() {<br>    onView(withId(R.id.<em>ibIncrement</em>))<br>        .perform(click())<br>    onView(withId(R.id.<em>ibDecrement</em>))<br>        .perform(click())<br>    onView(withId(R.id.<em>tvCounter</em>))<br>        .check(matches(withText(<strong>&quot;0&quot;</strong>)))<br>}</pre><ul><li>Wow, I believe we are improving as the line of the test cases is increasing, and we are getting to know more about Espresso.</li><li>Let’s check our third test case in which we need to check whether decrement button is working as per requirement or not.</li><li>To validate it, we need to click on the decrement button and then check the value of the TextView.</li><li>Both the things are covered in the first and second test cases, and there is no need to repeat them.</li><li>The question here is why there is a click performed on the increment button as well. Let’s see it in the next test case.</li></ul><p><strong>4. When user click on minus for the first time then it should not decrement the value to -1.</strong></p><pre>@Test<br><strong>fun </strong>shouldNotDecrementValueIfDecrementButtonIsClickedFirst() {<br>    onView(withId(R.id.<em>ibDecrement</em>))<br>        .perform(click())<br>    onView(withId(R.id.<em>tvCounter</em>))<br>        .check(matches(withText(<strong>&quot;0&quot;</strong>)))<br>}</pre><ul><li>In the beginning, the counter value is 0, and if we press the decrement button, then according to its functionality, it should decrement the count and make it -1.</li><li>But -1 value is not permissible for a counter, and hence we need to test this use case where decrement should not go beyond 0.</li><li>So when we performed a click on the decrement button without doing anything, then the value of the counter should remain 0 and not -1.</li><li>Hence, in the previous test case, we performed a click on the increment button first, which makes the counter value 1, and then click on the decrement button to make it zero and check the decrement button functionality.</li></ul><p>Let me categorise the methods we used in the test cases according to its functionality:</p><ul><li>ViewInteraction: onView(), perform(), check()</li><li>ViewMatchers: withId(), withText(), isDisplayed(), allOf()</li><li>ViewActions: click()</li><li>ViewAssertions: matches()</li></ul><p>Okay.. So that’s it for this blog on UI testing.</p><p><strong>Useful Links:</strong></p><p><a href="https://developer.android.com/training/testing/espresso/setup">https://developer.android.com/training/testing/espresso/setup</a></p><p><a href="https://developer.android.com/training/testing/ui-testing/espresso-testing">https://developer.android.com/training/testing/ui-testing/espresso-testing</a></p><p>Let me share my experience with UI testing. Currently, I’m working on a module along with my colleague at work. There are many instances where we work on the same file and change the logic written by each other. So, when we take a pull of each other’s code and resolve the conflicts, it is hard to manually test all the scenarios whether they are working or not. This is what made me a fan of testing code. Now, I simply run all the tests and check the result of the tests. It gives me confidence that the code is working perfectly fine if the tests pass.</p><p>I suggest developers who are reading this blog start writing the test cases for the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9cf0804f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Curious Case of Cosmos DB]]></title>
            <link>https://kunal-sale92.medium.com/the-curious-case-of-cosmos-db-914157f064d7?source=rss-70814551ef3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/914157f064d7</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[azure-cosmos-db]]></category>
            <dc:creator><![CDATA[Kunal Sale]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 05:39:50 GMT</pubDate>
            <atom:updated>2021-01-25T06:10:05.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n596JgD6HHkpdz1Nc8E3wg.png" /></figure><p>Recently, I got a chance to work on the Cosmos DB which is offered by Microsoft Azure. Initially it was fun writing CRUD operations on the DB. Once the things got complex, I had to take out the magnifying glass like in the above image, to get a closer look of the DB. Often the concepts and solution to a problem were interesting and increased the curiosity to learn more about it. So, I wanted to share some of the details which can help someone who wants to choose Cosmos DB or probably someone who is stuck.</p><h4><strong>Data Modelling (Normalise or Denormalise)</strong></h4><p>Cosmos DB is a Document based NoSQL database which is different from relational database. In relational database, we try to normalise the data by breaking an entity into a discrete components. In Cosmos DB, we should denormalise the data that is to keep every related thing of a particular entity in same document. As Cosmos DB doesn&#39;t support to write joins on different containers as we used to do in the relational database across the tables.</p><p>Suppose, there is an entity “Person” and its various components are “Address”, “ContactDetail”. In relational database, all the three components would have been in the separate tables and associated through the <strong>Public Key-Foriegn key </strong>mechanism. Picture will be different in Cosmos DB. There will be a document “Person” inside which there will be nested array of “Address” and “Address”.</p><pre>{<br>   &quot;first_name&quot;: &quot;Kunal&quot;,<br>   &quot;last_name&quot;: &quot;Sale&quot;,<br>   &quot;address&quot;: [{<br>       &quot;city&quot;: &quot;Mumbai&quot;,<br>       &quot;state&quot;: &quot;Maharashtra&quot;<br>    }],<br>   &quot;contact&quot;: [{<br>       &quot;phone&quot;:&quot;+1111111111&quot;,<br>       &quot;email_id&quot;:&quot;something@abc.com&quot;<br>   }]<br>}</pre><h4><strong>It’s all about the RU’s:</strong></h4><p>RU is basically Request Units which is used to calculate the throughput of a container. All the resources usage like CPU, IOPS(Input/Output Operation per second) and memory are considered under RU. Azure charges the usage of Cosmos DB on the RU consumption and it is on <strong>hourly basis</strong>. Now, you must have understood how important the RU is as its consumption is directly proportional to money you pay. There are two modes for setting the RUs.</p><ol><li><strong>Manual mode:</strong></li></ol><p>You can set RU for the Cosmos DB manually and Cosmos DB will give the throughput as per the RU given by you. In this mode, you need to know exactly how much is your consumption rate and load on the DB. If there is miscalculation in RU and you have got requests more than you expected, then be prepared for<strong> 429 To Many request error</strong>.</p><p>Let’s take an example, If you have set the RU to 400 and let’s consider 1kb document write operations will take 1RU so Cosmos DB can handled 400 write request at a time. Suppose, the load is 500 request now, then 400 requests will be served directly but rest 100 has to wait and has to do retry in order to get a chance. Here, Auto-scale comes into the picture.</p><p><strong>2. Auto-scale mode:</strong></p><p>In Auto-scale mode, you don’t have to worry about the RU calculation. It will auto-scale the RU if there is a load on the Cosmos DB and 429 error will not occur. So, you will think that if it auto-scales the RU and does it also downsize the RU once consumption is low?. Answer is yes. Also, pricing tier for the auto-scale is such that it considers the highest RU consumed in a given hour. So, you will be charged high only in the peak hours and most of the time it will be charged by the lowest bound.</p><p>Now, the question is which one to choose?</p><p>We can set the RU on database as a whole and also on containers separately. Keep the RU on the container level and set the manual RU’s for those you know that the consumption is low. Those containers for which you cannot predict exact consumption rate but you know that it will be on the higher side, simply enable the auto-scale mode and let Cosmos DB handle it.</p><h4><strong>Don’t be lazy to choose the Partition key!</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*GFFUGXriWlqfXGPJ7pvrPQ.jpeg" /></figure><p>Performance of the containers largely depends on Partition key. Cosmos DB distributes the data and makes the logical partitions by using Partition key. Documents with the same partition key will be stored in the same cluster (Logical partition). Using this mechanism, Cosmos DB ensures that the data operations are cheap and less expensive. Don’t confuse the partitioning with the Indexing. It is very important to choose an efficient partition key for the performance.</p><p>Few tips to use the partition key for improving the performance:</p><ul><li>Try to write queries that contains partition key because Cosmos DB can easily fetch the given document with minimum response time.</li><li>Choose a partition key which is unique throughout a container as it will distribute the partition evenly. But it cannot happen every time as you cannot find a partition key which will be unique for all the containers.</li></ul><p>That’s Okay. In order to achieve the efficient throughput even if the partition key is not unique, you have to evaluate your use case and use combination of the keys to make it a optimised query.</p><p><strong>Note: Partition key cannot be changed for a container after it is created. If you are planning to change the partition key then you have create a new container and migrate the data into it. Hence, don’t be lazy to choose you partition key wisely.</strong></p><h4><strong>Beware of Concurrency</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx62Gr_HS3l5yxrFtp396A.jpeg" /></figure><p>In a database, there are locks which means operation will wait until it gets the lock for the particular data. It makes sure that the data is uniform. Cosmos DB doesn’t lock the document on which the operation is currently happening. If there are concurrent write operations on the database, there is no assurance which document copy will get override the source.</p><p>Lets take an example:</p><pre>{<br> “first_name”: “John”,<br> “last_name”:”Doe”,<br> “employee_id”: 1,<br> “mobile_number”: “9999811222”,<br> “city”: “Mumbai”,<br> “state”: “Maharashtra”<br>}</pre><p>Suppose, there are 3 requests (R1, R2 and R3) which has read the above document on time T0. They modified the document accordingly to the businees logic. R1 changed the mobile_number to “9212121219”, R2 changed the city to “Bangalore” and R3 changed the state to “Karnataka”. And now they update their copies into the DB in the order R1, R2 and at last R3. Then, the result will be</p><pre>{<br> “first_name”: “John”,<br> “last_name”:”Doe”,<br> “employee_id”: 1,<br><strong> “mobile_number”: “9999811222”, ← R1 updated but it was overriden by R3</strong><br> <strong>“city”: “Mumbai”, ← R2 changed this to “Bangalore” but it was overriden by R3</strong><br> <strong>“state”: “Karnataka” ← Only the R3 changes got reflected because R3 copy didn’t have the changes made by the R1 and R2.</strong><br>}</pre><p>So, this is a major issue if the load is high and there are concurrent transactions on a particular document at a given time.</p><p><strong><em>Solution: Optimistic Concurrency: (_etag: The unsung hero)</em></strong></p><p>When the document is created in the container, there are few system defined parameters other than id. _etag is one of them and it keeps on changing whenever there is an update in the document. It can be used to avoid the data being overridden by the concurrent write operations.</p><p>It can be achieved by modifying the upsert operation as given below:</p><pre>// Update the data<br>function update(&lt;object_to_be_updated&gt;){<br>      return this.container.items.upsert(&lt;object_to_be_updated&gt;, {<br>          accessCondition: { <br>            type: “IfMatch”, <br>            condition: &lt;document_object&gt;._etag <br>          }<br>      });<br>}</pre><pre>//Fetch the data for the given id<br>function fetch(id){<br>      const querySpec = {<br>           query: `select * from c where c.id=&#39;${id}&#39;`<br>       };<br>      return await this.container.items.query(querySpec).fetchAll();<br>}</pre><pre>await update(&lt;object_to_be_updated&gt;)<br>      .then(updateResponse =&gt; {})<br>      .catch(async (error) =&gt; {<br>           if(error.code === 412){<br>             return await fetch(&#39;123&#39;) //the latest data is being fetched<br>                  .then(async (fetchedObject) {<br>                     return update(fetchedObject);  //Again the update is called with the fetched data<br>                  })<br>                  .catch(error =&gt; return error)<br>       });</pre><p>In the above code, <strong>accessCondition</strong> is the object being added in the upsert which sends the current object _etag. So while updating the document in the container, Cosmos DB checks whether the _etag in the source document is same as the _etag sent in the upsert. If it is doesn’t matches then it gives <strong>412 Precondition failure</strong> as an error which simply means that the document has been updated. In the catch, you have to fetch the latest document and again call the upsert with this document.</p><p>Let me summarise the points:</p><ol><li>Try to keep your data in a single document if possible (applicable only in NoSQL).</li><li>Keep an eye on your RU as it is what effect your pocket. 😆</li><li>Choose the partition key wisely as it will make your queries faster.</li><li>Optimistic concurrency is a mechanism to avoid the concurrent write operation and avoid loss of the data.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=914157f064d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Type System — How does it ensure null safety?]]></title>
            <link>https://kunal-sale92.medium.com/kotlin-type-system-how-it-ensures-null-safety-790699f721?source=rss-70814551ef3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/790699f721</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[nullpointerexception]]></category>
            <category><![CDATA[operators]]></category>
            <dc:creator><![CDATA[Kunal Sale]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 18:35:02 GMT</pubDate>
            <atom:updated>2022-03-03T17:27:47.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*XjpK05JX9mhPpMBis2SrIw.png" /></figure><p>Kotlin Type System provides a way to handle <strong><em>null values</em></strong> and avoid <strong><em>NullPointerExceptions</em></strong>. Kotlin doesn’t <strong><em>implicitly</em></strong> support null values i.e We need to specify whether the <em>particular type can be null or not</em>.</p><p>Let’s see how the type system in Kotlin works.</p><pre>fun strLen(str: String) = str.length</pre><p>In above function, str can never be null as it is not specified in the signature that the str can be null. Calling the function with null value will give a compile time error that null cannot be passed to non-null type</p><p>&gt;&gt; strLen(null)<br>&gt;&gt; Error: <strong><em>null cannot be a value to non-null string.</em></strong></p><p><strong><em>Nullable Types</em></strong></p><p>Kotlin makes sure that once the variable is declared non-null, then null value cannot be assigned to the variable by making the check in the compile time and avoiding NullPointerException at runtime.</p><p>There might be a case when we need to pass null values. So, How can we pass null value to the function?</p><p>Answer is by making the <em>variable of Nullable type</em>.</p><pre>fun strLen(str: String?) = ...</pre><p>By adding <strong>?</strong> at the end of type makes the variable of Nullable type that can hold null values. Now, we can call function strLen with null value.</p><p><strong>Note</strong>: Kotlin encourages you to make use of non-nullable type variable over nullable type variable. By doing this, you ensure null safety in your code and also there is performance advantage in some cases. Let’s see how.</p><p>As you know kotlin is converted to java code at compile time to create byte code file. So, If we declare an <strong>Int? variable</strong>, it will get converted to wrapper class <strong>Integer.</strong></p><p>var age: Int? → Integer age;</p><p>Instead if we create <strong>Int variable</strong>, then it will get converted to <strong>primitive type int.</strong></p><p>var age: Int = 0→ int age = 0</p><p>So, make use of non-nullable types as much as you can.</p><p><strong>Null Safety</strong></p><p>Now, we know variable can be made nullable and can make method call on the object. In our example of strLen(), we made str as nullable and we are calling str.length in the function block which can result in NullPointerException. We need to avoid calling length on null value.</p><p>One possible solution is by adding null check in the function.</p><pre>fun strLen(str: String?): Int {<br>    if(str != null){<br>       return str.length  <br>     }<br>     else{<br>      return 0<br>     } <br>}</pre><p>But, It’s Java way of handling NullPointerException and code is also pretty verbose. Kotlin has got some exciting operator for such task and they are much compact and handy.</p><ul><li><strong><em>Safe call Operator (?)</em></strong></li></ul><p>It is most commonly used operator to avoid NullPointerException. It combines <strong>null</strong> check and <strong>method call </strong>in a single operation<strong>. For example, str?.toUpperCase() is same as if(str != null) str.toUpperCase() else null.</strong></p><pre>fun printAllCaps(str: String?){<br>   println(str?.toUpperCase())<br>}</pre><pre>&gt;&gt; printAllCaps(&quot;kotlin&quot;)<br>&gt;&gt; KOTLIN</pre><pre>&gt;&gt; printAllCaps(null)<br>&gt;&gt; null</pre><p>Safe call is also useful when we need to add null checks for multiple objects and its related variables. For example:</p><pre>class Person{<br>   var addresses: List&lt;String&gt;? <br>   var name: String<br>   var age: Int<br>} </pre><pre>if(person != null &amp;&amp; person.addresses != null){<br>   val personalAddress = person.addresses.get(0)<br>}</pre><pre>with safe operator it can be re-written as</pre><pre><strong><em>val personAddress = person?.addresses?.get(0)</em></strong></pre><ul><li><strong><em>Elvis operator (?:)</em></strong></li></ul><p>Above code can be changed by using elvis operator.</p><pre>fun strLen(str: String?): Int {<br>  return <strong>str?.length ?: 0</strong><br>}</pre><p>What elvis operator does is, it first checks whether the object is null or not. If object is not null, then it will return object value which is on the left side. If the object is null, then it will return value which on the right side of the operator.</p><p><strong>Elvis is also used to throw exceptions</strong> where some condition is not satisfied. Let’s take an example where null argument is passed to the method.</p><pre>fun sendParcel(person: Person){<br>   val address = person?.address <strong>?:</strong> throw IllegalArgumentException(&quot;Address not passed&quot;)<br>  .<br>  ...<br>}</pre><p>Here, If address is null, then throw an Exception which will tell the developer to pass the required arguments.</p><ul><li><strong><em>Non-null Assertion (!!)</em></strong></li></ul><p>This operator is used to tell the compiler that the object on which some operation is going to perform is not null. Sometimes we know that at a given time object is not going to be null. So, we use non-null assertion on nullable object to tell the compiler that it is not going to be null.</p><pre>fun strlen(str: String?){<br>    str = &quot;Non-Null&quot;<br>    return <strong>str!!.length</strong><br>}</pre><p>In above example, we have explicitly assigned a value to the str variable. So, we have (!!) instead of (?) as we know the variable will not be null.</p><p>Note: Use Non- null (!!) in cases where you are sure that object is not going to be null. If you are not sure and accidentally null is passed to the object, then we can get NullPointerException.</p><ul><li><strong><em>Let block</em></strong></li></ul><p>How inline functon let helps us to prevent NullPointerException, Let’s see.</p><pre>&gt;&gt; var emailId: String? = null</pre><pre>&gt;&gt;<strong><em> emailId?.let {    (1)<br>  sendEmail(it, body) (2)<br>}</em></strong></pre><pre>&gt;&gt; fun sendEmail(emailId: String, body: String){<br>   // call some api to send an email<br>}</pre><pre>1. let is called on Nullable object which enters the block with &#39;it&#39; value if emailID is not null.<br>2. sendEmail is called with &#39;it&#39; and body as &#39;it&#39; is emailId and it is not null.</pre><p><strong>When let is used on nullable objects, then it enters the block only if the object is not-null</strong>. If object is null, then it will skip the block.</p><p><strong>Note</strong>: let is used on both <strong>Nullable and Non-Nullable types</strong> as it is primarily used to skip calling every parameter with object name and return any result. It gives <strong>advantage of Null safety</strong> when used with Nullable type by only entering the scope if object is not null.</p><ul><li><strong><em>Late-init initializer (late init)</em></strong></li></ul><p>In Kotlin, every variable has to be given an initial value at the time of declaration. If variable is off non-primitive datatype, we make variable Nullable and assign null value to the variable. This way we need to add null safety check or operator’s to avoid NullPointerException. Kotlin has got late init initializer to avoid this mistake.</p><p>By using late init on variable, <strong>we don’t have to assign any value to the variable at the time of declaration</strong>. But, we need to make sure that we initialize the variable before its usage.</p><pre>var person: Person? = null<br>person<strong>?.</strong>age = 25<br>person<strong>?.</strong>address = &quot;Mumbai, Maharashtra&quot;</pre><pre>------------------------------------------------</pre><pre>lateinit var person: Person<br><strong>person = Person() </strong><br>person.age = 25<br>person.address = &quot;Mumbai, Maharashtra&quot;</pre><pre>Here, you can see how safe call operator is avoided by marking the variable with lateinit. But we have make sure that we initial the variable before its call. </pre><p>Above are some techniques that can be used to ensure null safety in our code.</p><p>Hope, you understood how Kotlin makes it easy to avoid NullPointerException and offers tools to make it happen.</p><p><em>Thank you for reading…….</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790699f721" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>