<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Rivu Chakraborty]]></title><description><![CDATA[Kotlin Advocate, Google Developer Expert, Android Dev & Enthusiast, Public Speaker, Author of Multiple Kotlin Books. Founder. ADHD]]></description><link>https://rivu.dev/</link><image><url>https://rivu.dev/favicon.png</url><title>Rivu Chakraborty</title><link>https://rivu.dev/</link></image><generator>Ghost 4.48</generator><lastBuildDate>Sat, 11 Apr 2026 19:56:12 GMT</lastBuildDate><atom:link href="https://rivu.dev/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Why I Chose Compose Multiplatform for FretPractice (And Why It Wasn't an Easy Call)]]></title><description><![CDATA[<p>Hi everyone. It&apos;s been a while, a long, long while. I haven&apos;t published a blog in what feels like forever.</p><p>Honestly, it&apos;s not that I stopped writing. I just kept feeling like what I had wasn&apos;t quite ready to put out. So</p>]]></description><link>https://rivu.dev/fretpractice-compose-multiplatform-why/</link><guid isPermaLink="false">69ae2ff99b71c2001cceb6e6</guid><category><![CDATA[Android]]></category><category><![CDATA[compose]]></category><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Rivu Chakraborty]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Thu, 26 Mar 2026 17:39:07 GMT</pubDate><media:content url="https://s3.amazonaws.com/rivu.dev-new/2026/03/Screenshot-2026-03-26-at-9.32.37-PM.png" medium="image"/><content:encoded><![CDATA[<img src="https://s3.amazonaws.com/rivu.dev-new/2026/03/Screenshot-2026-03-26-at-9.32.37-PM.png" alt="Why I Chose Compose Multiplatform for FretPractice (And Why It Wasn&apos;t an Easy Call)"><p>Hi everyone. It&apos;s been a while, a long, long while. I haven&apos;t published a blog in what feels like forever.</p><p>Honestly, it&apos;s not that I stopped writing. I just kept feeling like what I had wasn&apos;t quite ready to put out. So here we are, finally breaking that streak.</p><p>If you don&apos;t know already, I&apos;ve started a new venture: <strong><a href="https://mobrio.studio">Mobrio Studio</a></strong>, where I&apos;m building <strong><a href="https://fretpractice.com">FretPractice</a></strong>. It&apos;s built on Compose Multiplatform, and I figured writing about that platform choice might add some value to the community.</p><p>If you know me, you might think that&apos;s an obvious answer, I&apos;m pretty loud about KMP. But trust me, it wasn&apos;t that straightforward. Read on.</p><hr><h2 id="my-take-on-kotlin-kmp-and-compose-multiplatform">My Take on Kotlin, KMP, and Compose Multiplatform</h2><h3 id="kotlin">Kotlin</h3><p>I&apos;ve been a Kotlin advocate for a long time. Wrote books on it 8 years ago, and more than half my blog posts are Kotlin-related in some way. Safe to say I&apos;m a fan, you wouldn&apos;t be wrong to call it love.</p><h3 id="kotlin-multiplatform">Kotlin Multiplatform</h3><p>Same story here. When it comes to sharing business logic across platforms, KMP has no real competition. No other technology lets you write code in one language and ship it natively, compiled to native binaries, as libraries across platforms. Yes, you can do something similar with C++ or even Rust via <a href="https://en.wikipedia.org/wiki/Foreign_function_interface">FFI</a>, but the added complexity only makes sense when you need low-level control for performance or security. For regular business logic sharing, KMP is the best choice, full stop.</p><p>One honest caveat though: KMP has a steep learning curve for production apps. If you&apos;re going this route, make sure you have a senior engineer on the team who actually knows the ropes.</p><h3 id="compose-multiplatform">Compose Multiplatform</h3><p>Here&apos;s where things get nuanced.</p><p>I love Compose as an Android developer, it makes life genuinely easier. Yes, it has its quirks, and understanding Declarative UI takes some time to click, but once it does, Compose is great. And the Android team keeps improving it (keep an eye on Compose Styles if you haven&apos;t already).</p><p>That said, I&apos;ve always had a strong preference for native UIs. Native means fewer platform-check conditionals cluttering your UI logic, a more intuitive feel per platform, and better performance.</p><p>Here&apos;s the thing about Compose Multiplatform: while KMP compiles to native binaries (LLVM on iOS/macOS, JVM bytecode on Android, minified JS on web), Compose Multiplatform can&apos;t do the same, it has to handle drawing itself (<em>note, your app still does compile to native binaries, it just now has an added engine to draw ui</em>). On iOS, for example, SwiftUI talks directly to Core Animation and Metal. Compose Multiplatform has to go through Skiko first, which then delegates to Metal. That extra layer isn&apos;t free, it costs performance.</p><p>The tradeoffs get broader as you add more target platforms. On Web with Wasm/JS, you give up standard web features like per-screen URLs and SEO. On Desktop, you&apos;re no longer shipping a native app per platform, you&apos;re shipping a JVM app.</p><p>So no, I&apos;ve never been as enthusiastic about Compose Multiplatform as I am about Kotlin or KMP. My position on shared UI has always been skeptical.</p><h3 id="flutter">Flutter</h3><p>Contrary to what some might expect, I actually like Flutter. It lets you move fast, and for most apps that don&apos;t have heavy native dependencies, it&apos;s a solid choice. The learning curve is short and intuitive regardless of your background, that&apos;s genuinely hard to replicate.</p><p>If someone asks me to pick between Flutter and Compose Multiplatform for a standard CRUD app with no special constraints, I&apos;d probably go Flutter. Even with my feelings about Dart.</p><hr><h2 id="so-why-compose-multiplatform-for-fretpractice">So Why Compose Multiplatform for FretPractice?</h2><p>The short answer: it&apos;s still the best fit for where I am right now, one developer, moving fast, building something that needs to ship.</p><p>But here&apos;s why it&apos;s not a simple answer.</p><p>FretPractice isn&apos;t just another focus or practice timer app. It&apos;s a music app. It needs DSP logic to accurately detect notes in real time. It&apos;ll have DRM for AI-generated music. It&apos;ll include DAW features - stem splitting, editing, production. And down the line, it needs to talk to hardware over Bluetooth and Wi-Fi.</p><p>That rules out Flutter entirely. The native dependencies are too deep.</p><p>But building fully native UIs for 8 platforms (Android, iOS, JVM Desktop, Web, watchOS, Wear OS, Android TV, Apple TV), is simply not feasible for a solo developer trying to actually launch something. So Compose Multiplatform is the pragmatic next-best choice.</p><p>Despite all the tradeoffs I laid out, it still inherits KMP&apos;s biggest strength: wiring in native code while sharing business logic efficiently. And the one KMP learning-curve caveat I mentioned? Doesn&apos;t apply when you&apos;re the one building it.</p><p>Also worth noting: if you structure your project well, replacing Compose Multiplatform UI with native UI later, while keeping the shared KMP logic intact is a much smaller lift than rewriting the whole thing from scratch.</p><p>That&apos;s the bet I&apos;m making.</p><hr><p>And that&apos;s really the point of this post, the &quot;right&quot; platform choice doesn&apos;t exist in a vacuum. It depends on what you&apos;re building, who&apos;s building it, and what constraints you&apos;re working within. If you&apos;re building a CRUD app solo and need to ship fast, maybe Flutter is your answer. If you have a team and the time, maybe full native is worth it. For me, right now, with FretPractice, Compose Multiplatform is the call that makes sense.</p><p>Anyway, it feels good to be writing again. I&apos;ve got a lot more to share as <a href="https://fretpractice.com">FretPractice</a> takes shape, the architecture decisions, the DSP work, the multiplatform quirks I run into along the way. If any of that sounds interesting, stick around. </p>]]></content:encoded></item><item><title><![CDATA[Why Emitting State from Repository is an Anti-Pattern]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>In this post, as the title suggests, I&apos;ll discuss why one shouldn&apos;t emit View States (or as some people prefer to call it Resource nowadays) from Repository, and why is it Anti-Pattern IMO. While discussing that, this post will also address why returning <code>LiveData</code> from Repository</p>]]></description><link>https://rivu.dev/why-emitting-state-from-repository-is-an-ani-pattern/</link><guid isPermaLink="false">673f82cc0b613e001cb86a87</guid><category><![CDATA[AndroidDev]]></category><category><![CDATA[Android]]></category><category><![CDATA[jetpack]]></category><category><![CDATA[optimisation]]></category><category><![CDATA[LiveData]]></category><category><![CDATA[ViewModel]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Sun, 05 Jul 2020 10:29:37 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/07/ViewStateAndViewModel.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/07/ViewStateAndViewModel.jpg" alt="Why Emitting State from Repository is an Anti-Pattern"><p>In this post, as the title suggests, I&apos;ll discuss why one shouldn&apos;t emit View States (or as some people prefer to call it Resource nowadays) from Repository, and why is it Anti-Pattern IMO. While discussing that, this post will also address why returning <code>LiveData</code> from Repository doesn&apos;t make sense.<br>
So let us get started by understanding each of the layers in an Android app, and their purposes/function.<br>
<strong>Note</strong>: I&apos;m not advocating structuring your project by layer here, in-fact I prefer structuring by feature. However, the layers are still there within feature-based modules or packages (in case of monolithic apps).</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h2 id="layersinatypicalandroidapp">Layers in a typical Android App</h2>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>There can be multiple layers in an Android app, however, 3 of them are most significant.</p>
<ul>
<li>UI</li>
<li>Presentation</li>
<li>data</li>
</ul>
<p>Now, we can divide each of these layers into smaller sub-layers, for example, data layer can be divided into <em>cache</em> and <em>remote</em> sub-layers, but let&apos;s focus into these 3 major layers, and try to understand their purpose and functionality.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="datalayer">data Layer</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>As the name suggests, this layer is supposed to be dealing with all data fetching, caching, storing, manipulating, and all other data related operations. In the earlier days of Android, we used to have <code>DataModels</code> in this layer, which in most cases were a single class, dealing directly with DB or DAO and Remote / Network. As we, Android Developers worldwide started becoming more and more cautious about the separation of concern and clean code, we realized that we need to separate out cache and remote.<br>
That&apos;s when the concept of Repository came up. Yes, the concept of Repository isn&apos;t tied to MVVM architecture, and you can still use it (and you should) with any other arch pattern you use, including MVP.<br>
So, what is the responsibility of a Repository? Simple, manage all data transactions, decide on when to fetch the data from remote and when to fetch it from the cache, etc. Ideally, a Repository should come with <code>DataStore</code>s, based on your requirement, you can have RemoteDataStore or CacheDataStore or both. A RemoteDataStore should contain all the logic to fetch data from remote APIs, if you&apos;re using <strong>Retrofit</strong> in your app, RemoteDataStore is where you call the API interface. Similarly in CacheDataStore, you put all local storage related logic. One thing to note here is that the names are nonsubstantial IMO, I know a lot of good people who prefers to call it <em>NetworkManager</em> instead of <em>RemoteDataStore</em>, and in my opinion, there&apos;s nothing wrong with it.<br>
TLDR about data layer: It contains Repository, which should contain only data-transaction related code. Now Repository in turn might have dependencies on Remote/Network and Cache/Local DataStore(s).<br>
Now let us discuss the next layer - the presentation layer.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="presentationlayer">Presentation Layer</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Presentation is where you keep your business, i.e. the business logic. If you follow MVP, then you have your presenter here, if you follow MVVM, then you have your ViewModel here, one thing to note here is that ViewModels are also used multiple other architectures, including MVI, etc. So, as the goal of this post is to discuss ViewState and LiveData, let us assume, you have <code>ViewModel</code> here.<br>
So, what is the purpose of ViewModels? a common answer is to hold the business logic, but actually, that&apos;s not all, if you ever think, why is it called ViewModel, instead of Presenter with Stream or something like that, then it becomes clear; along with a place to keep your Business logic, a ViewModel should also maintain the ViewState or State (or as some people prefer to call it - Resource).<br>
Now, what is a ViewState? A View state is nothing but a simple POJO or data class, which will hold the current state of the View, and ideally, a View should render the exact ViewState.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="uilayer">UI Layer</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>The UI layer is where you should keep your UI designs and ViewState rendering logic. Ideally, the UI layer should subscribe to the presentation layer, to get updated ViewState, and render it, and pass the UI events (such as click) to the presentation layer. This layer consists of Activities, Fragments, custom Views, etc.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h2 id="whatswronginemittingstatefromrepository">What&apos;s wrong in emitting State from Repository</h2>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>The are multiple reasons why you shouldn&apos;t emit States from Repository, we&apos;ll look at the two most important points here (IMO).</p>
<ol>
<li>As we discussed above, it is ViewModel&apos;s job to maintain the State. The data layer should never be aware of anything related to the view or ViewState (for eg. whether view state is loading or showing error or success etc.) the data layer should only be caring about fetching and storing data, nothing more, nothing less. Moreover, if ViewModels emit State / ViewState / Resource, then it&apos;s more likely that you might end up having at least some part of business logic in the Repository, as you&apos;d generally want the states to be based on business logic.<br>
So, it&apos;s evident enough that Repository, which is part of the data layer, should never be emitting ViewState.</li>
<li>As your app grows and becomes more complex, you might separate the data layer as a separate module. Also, you might wanna re-use a Repository from multiple ViewModels, for example, you have a Repository, say <code>UserProfileRepository</code> that manages <code>UserProfile</code> which is mostly used in the profile page, now you have a subscription page, where you need <code>UserProfile</code> again, so if you copy the same code to <code>SubscriptionRepository</code> then there&apos;ll be redundancy, rather you might wanna call both <code>SubscriptionRepository</code> and <code>UserProfileRepository</code> from <code>SubscriptionViewModel</code> and map/flatMap the data according to your business logic. Now, if you have Repositories emitting States / Resources / ViewState, using multiple Repositories would get more complex for you.</li>
</ol>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h2 id="whylivedatainrepositorydoesntmakesense">Why LiveData in Repository doesn&apos;t make Sense</h2>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>To understand why LiveData in Repository or the data layer doesn&apos;t make sense, we need to understand what is LiveData and why was it created. LiveData wasn&apos;t created to replace Rx or Coroutines, it was created as a simple reactive state-change wrapper. You&apos;d publish updates from one end, and would subscribe to it from the other end. The main reason why they created LiveData was to remove subscribing and cleanup complexities from View/UI layer. Generally, we want to subscribe to Stream in Activity/Fragment/View, and we need to remember to dispose of the subscriptions when the View is destroyed. Sometimes we also want to avoid receiving updates when our View (Activity/Fragment/View) is in background. Now all these are possible with Rx or Flow or any other full-fledged streaming mechanism, but that was a little complex and a lot of boilerplate, which can lead to human mistakes. Moreover, generally in these cases, we don&apos;t want heavy modifications/operations on the data (such as flatMap/map, etc.), since the data here is basically the state, and it&apos;s ready to be rendered. So, Google created a <em>lightweight reactive stream</em> called LiveData. Now, if you return/use LiveData in the data layer, that means you&apos;re restricting the possibility to map/flatMap the data at the presentation layer, unless you use MutableLiveData at multiple layers, and over-complicate your codebase. Also, if you ever have written unit tests with LiveData, then you are probably aware, that test classes you either need to implement a <code>TaskExecutor</code> or you need to use <code>InstantTaskExecutorRule</code>, which tells the LiveData that the observation is in Main Thread. This clearly indicates that LiveData observations are always in Main Thread. That&apos;s expected behavior when you&apos;re subscribing to the LiveData from your UI/View layer, but do you really want that in your presentation/data layers? Yes, there can be hacks or even ad-hoc mechanisms to have the observation run on other threads, but does it make sense to overcomplicate things when there&apos;s plenty of other options?</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h2 id="tldr">TLDR</h2>
<p>Don&apos;t use LiveData in the data layer, which includes Repository, and don&apos;t emit ViewState/State/Resource from Repository.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Breaking the ice: Service Locator and Dependency Injection Which is What]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There is a very thin lining of difference between <strong>Service Locator (in short SL)</strong> and <strong>Dependency Injection (in short DI)</strong>. Most people get confused with these terms, even I was confused with them for so long. Even more so for Android Developers, most of us often get in dilemma whether</p>]]></description><link>https://rivu.dev/service-locator-and-dependency-injection-which-is-what/</link><guid isPermaLink="false">673f82cc0b613e001cb86a86</guid><category><![CDATA[AndroidDev]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[DI]]></category><category><![CDATA[Dependency Injection]]></category><category><![CDATA[SL]]></category><category><![CDATA[Service Locator]]></category><category><![CDATA[Dagger]]></category><category><![CDATA[Koin]]></category><category><![CDATA[Dagger vs Koin]]></category><category><![CDATA[DI vs SL]]></category><category><![CDATA[Android]]></category><category><![CDATA[IoC]]></category><category><![CDATA[Inversion of Control]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Fri, 12 Jun 2020 18:31:34 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/06/coffee-writing-computer-blogging-34600.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/06/coffee-writing-computer-blogging-34600.jpg" alt="Breaking the ice: Service Locator and Dependency Injection Which is What"><p>There is a very thin lining of difference between <strong>Service Locator (in short SL)</strong> and <strong>Dependency Injection (in short DI)</strong>. Most people get confused with these terms, even I was confused with them for so long. Even more so for Android Developers, most of us often get in dilemma whether to use Koin or Dagger in their project. In this blog, I&apos;ll try to answer the questions regarding SL and DI, and will try to define them using simple terms, and will also compare Dagger and Koin for Android environment so that you can make the decision your self. But if you ask me for a one-sentence answer on whether to use Dagger or Koin in your project, my answer will be &quot;it matters&quot;.</p>
<p>The goal of this blog isn&apos;t to show how to use Koin or Dagger, rather the goal is to clear the area around the DI and SL concepts, and comparing and differentiating Dagger and Koin so that it&apos;s easy for you to decide which one is best suited for your project.</p>
<h3 id="inversionofcontrolioc">Inversion of Control (IoC)</h3>
<p>First thing first, all of this DI and SL comes from the IoC principle, so let us understand the IoC principle first. IoC or Inversion of Control or Dependency Inversion is the D of SOLID principles. We&apos;ll not go to all the bookish definitions, what IoC says is, in short, a class that is using a dependency shouldn&apos;t create it, rather than should be provided the dependency with. So, instead of creating the dependant class first, and then let the dependant class create the dependency, the dependency class should be created and provided to the dependant by a third party.</p>
<h4 id="whataredependencyanddependant">What are <code>Dependency</code> and <code>Dependant</code>?</h4>
<p>As we discussed a class shouldn&apos;t create its own dependencies, the question comes what exactly is a dependency? Let us take some real-life examples to answer that. If you&apos;re following MVVM architecture pattern in Android, you might access the ViewModel class from Activity / Fragment / View. So, your view (Activity / Fragment / View) class depends on that ViewModel instance, so the ViewModel instance is <strong>dependency</strong> and the view (Activity or Fragment or View) class is the <strong>dependant</strong>.</p>
<h3 id="whatsdependencyinjectiondi">What&apos;s Dependency Injection (DI)?</h3>
<p>Dependency Injection is a pattern/principle that provides a way to incorporate IoC. It says the dependency should be injected to the dependant. You can take the word &apos;inject` to its literal meaning here, much like the injections in real life, in DI, the dependant doesn&apos;t know how the dependency would come or from where, it just uses the dependency when it needs, and a third party injects that dependency right after the dependant instance is created.<br>
In DI, it&apos;s important that a class should never know where the dependency comes from, or should never request for the dependency itself (if you don&apos;t know where it&apos;s coming from, you can&apos;t request as well).</p>
<p><strong>Note</strong>: DIP and DI aren&apos;t the same thing. DIP means Dependency Inversion Principle, while DI means Dependency Injection, which is a way of incorporating DIP.</p>
<h3 id="whatsservicelocatorsl">What&apos;s Service Locator (SL)?</h3>
<p>Just like DI / Dependency Injection, Service Locator is also a pattern/principle that provides a way to incorporate IoC/DIP, just that SL isn&apos;t as strict as DI. It also says the dependency should be provided to the dependant, but in contrary to DI, here the dependant class can request for the dependency in various forms. This can give a big benefit - for example, the dependant class can request for the dependency only when it needs to use it.</p>
<h3 id="isconstructorinjectionatypeofservicelocatorsl">Is Constructor Injection a type of Service Locator (SL)?</h3>
<p>I believe yes since, with Constructor Injection, the class explicitly asks for the dependency to be passed down to it while creating the instance, which contradicts the DI principle. DI says the dependant should never ask for the dependency in any form or manner.</p>
<h4 id="soisconstructorinjectionabadpractice">So is Constructor Injection a bad practice?</h4>
<p>Quite the contrary, you should rely on Constructor Injection whenever possible. It makes it more readable and keeps it free from framework interference, for example, if you change the DI framework for your project tomorrow, you won&apos;t need to make changes to the dependant class, as its dependencies are passed down the constructor, it&apos;d be same for any DI/SL framework you use.<br>
Moreover, Constructor Injections make it easy for you to test. In my opinion, while writing Unit tests, it&apos;s easy to provide the dependencies with Constructor Injection, than with any other methods.<br>
Also, note here, Constructor Injection is not DI per se, but it is definitely an implementation of IoC.</p>
<h3 id="whatisdagger">What is Dagger?</h3>
<p>Most of Android Developers confuse DI with Dagger. If you casually ask an Android developer, &quot;Hey, do you use DI&quot;, more than often you&apos;ll get answers like &quot;(no we don&apos;t / yes we) use dagger&quot;. That sums up how much popular Dagger became in the Android community lately, that. people mixup DI with Dagger. So what is Dagger? Dagger is a framework that helps you implement DI. the difference between DI and Dagger is the same as between DI and Dagger is similar to that of Car and <a href="https://www.rolls-roycemotorcars.com/en_US/showroom/phantom-ewb.html">Rolls Royce Phantom</a>.<br>
What Dagger does is that it lets you annotate dependencies of your class with <code>@Inject</code> annotation (from JSR330), so it can proactively provide those dependencies for you to the dependant class.<br>
Now, it&apos;s worth noting here that Dagger or any other DI/SL framework for that matter doesn&apos;t know how to create instances of those dependencies, you&apos;ll have to tell that to the framework, for Dagger, we generally do that in a module file, or sometimes even in the dependency class with <code>@Provides</code> annotation.<br>
So what happens when you annotate a dependency with <code>@Inject</code> but Dagger doesn&apos;t know how to create that instance? The answer is simple, your build will fail. To understand why we need to understand how dagger works.</p>
<h4 id="howdaggerworks">How Dagger works?</h4>
<p>We can&apos;t explain everything in Dagger in a single post, but here I&apos;d try to give a brief idea of how Dagger code generation works.<br>
Dagger uses annotation processing to generate necessary code, that&apos;ll inject the dependency in your dependant class. To explain it further, let us say you have an <code>Activity</code>/<code>Fragment</code>, and you are trying to inject your <code>RecyclerView.Adapter</code> to that Activity/Fragment, so you annotated <code>adapter</code> variable in your Activity/Fragment with <code>@Inject</code>, so when you build the code, annotation processing will take place, and Dagger will generate a file named like <code>ActivityName_MembersInjector</code>, let us consider the Activity/Fragment is named as <code>HomeScreen</code>, the injector class name would be <code>HomeScreen_MembersInjector</code>. Now if you navigate to that generated file, you&apos;ll see that it has a dependency on a <code>Provider&lt;T&gt;</code> for the <code>adapter</code>, so if we consider your adapter&apos;s name is <code>HomeAdapter</code>, then <code>HomeScreen_MembersInjector</code> would have a dependency on <code>Provider&lt;HomeAdapter&gt;</code>.<br>
Now the question is how Dagger will get the provider instance to pass it on to the injector? The answer is simple, for every <code>@Provides</code> annotation you write, Dagger generates a Provider class for that dependency.<br>
So if Dagger can&apos;t find a Provider class for any dependency while generating the code, it&apos;ll fail the build.</p>
<h3 id="whatskointhenandhowitworks">What&apos;s Koin then and how it works?</h3>
<p>Koin is another library enabling IoC, it relies on SL pattern rather than DI. Koin utilizes Kotlin&apos;s delegation system for providing the dependencies, rather than generating code do to that. With Koin you&apos;ll write something like <code>val adapter: HomeAdapter by inject()</code>, basically you&apos;ll use a function named <code>inject()</code>, which in turn uses <a href="https://kotlinlang.org/docs/reference/delegated-properties.html#lazy">Koilin&apos;s <code>lazy</code> delegation</a>. Kotlin&apos;s <code>lazy</code> delegation allows you to instantiate a <code>val</code> property (final variable) when it&apos;s first used, so if you declare a variable, and use <code>lazy</code> delegation to initialize it, and never use the variable, at runtime, the variable will never be initialized.<br>
So, what happens with Koin&apos;s <code>inject()</code> delegation, is that the class asks for the dependency when it needs at the runtime and then, in turn, Koin searches if you mentioned how to create that dependency in a Koin <code>module</code>, provides the dependency if you did, or throws a <code>RuntimeException</code> if you didn&apos;t (there&apos;s a solution for that though).</p>
<h3 id="isdipossiblemanually">Is DI possible Manually?</h3>
<p>Absolutely, it requires a lot of effort though to get proper DI manually. What does Dagger do? It generates the code that does the DI, so obviously DI is possible manually, however, think of the volume of code Dagger generates, I&apos;m not sure you&apos;d like to write all that code yourself for every class and all of its dependencies.</p>
<h3 id="whatshouldidothendiorslanddaggerorkoin">What should I do then DI or SL and Dagger or Koin?</h3>
<p>The correct answer depends on your team and project size and requirements. Both DI and SL have their fair share of advantages and disadvantages. However, there&apos;s one type of SL, that you should always prefer to use whenever possible, that is Constructor Injection (strictly my opinion).<br>
You can use Constructor Injection with both Dagger and/or Koin, so irrespective of the framework you use, it enables you to use IoC / DIP easily. In other words, Constructor Injection helps you achieve KISS.</p>
<p>For Dagger vs Koin, again the choice depends on multiple factors including your project size and requirements, but here are a few pointers that can both be in advantage or disadvantage based on your project/requirement.</p>
<ul>
<li>Koin resolves the dependencies at runtime whereas Dagger resolves them at compile time. Now, if you look at it, doing it at runtime might be in your favor, especially if you want your dependencies to be loaded lazily, however, as I pointed out before this can sometimes lead to unwanted surprises and even crashes. If you use Koin or any other SL, you need to have tests in place to make sure there are no surprises. Thankfully Koin provides a gradle task along with a test mechanism to do just that.</li>
<li>Dagger/Hilt provides a way to automatically bind your Dynamic Feature modules, however with Koin, you need to manually bind them as the modules get downloaded.</li>
<li>Dagger also has the option of providing dependencies lazily, with it&apos;s <code>Lazy</code> wrapper, but with <code>Lazy</code> as well, Dagger automatically resolves the dependencies at compile time to generate providers, so you&apos;re safe. Many people believe that <code>Lazy</code> is a way to do SL with Dagger.</li>
<li>One common argument we get against Dagger is &quot;The ugly <code>public lateinit var</code>&quot;, this can be easily avoidable with Constructor Injection for the most part, only for the Framework classes, you&apos;ll need this. Now, it&apos;s your decision whether you want to avoid Dagger for this or you&apos;d consider it as a tradeoff.</li>
</ul>
<p>To conclude, we can say the choice between DI and SL or Dagger and Koin is much like a choice between Statically Typed Languages (like Kotlin) and Dynamic Languages (like Python, etc.) none of these are bad, and both have their fair share of advantages or disadvantages, however, either one is better suited in a given scenario, while the other one might be better suited in some other scenario.</p>
<p><strong>Disclaimer:</strong> Most of this post is based on my understanding, and my opinions. Also, it&apos;s worth noting here, that some good people believe Constructor Injection is DI, not SL, I wrote here what I believe to be appropriate.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Writing Unit Tests efficiently in Android with Spek]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Ever thought organizing test cases in Android are cumbersome? For instance, you have a function and there are 3 scenarios you want to test, for example, for 3 different inputs, it&apos;s supposed to return 3 different outputs, and you want to test this behavior, now what we mostly</p>]]></description><link>https://rivu.dev/unit-testing-in-android-with-spek/</link><guid isPermaLink="false">673f82cc0b613e001cb86a80</guid><category><![CDATA[Android]]></category><category><![CDATA[AndroidDev]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Unit Test]]></category><category><![CDATA[Test]]></category><category><![CDATA[DSL]]></category><category><![CDATA[Spek]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Sun, 19 Apr 2020 16:00:00 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/spek-cover.png" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/spek-cover.png" alt="Writing Unit Tests efficiently in Android with Spek"><p>Ever thought organizing test cases in Android are cumbersome? For instance, you have a function and there are 3 scenarios you want to test, for example, for 3 different inputs, it&apos;s supposed to return 3 different outputs, and you want to test this behavior, now what we mostly do in Android and <code>JUnit 4</code> is create 3 different functions and name the functions like</p>
<pre><code class="language-kotlin">fun `test functionName should return output1 for input1`()
</code></pre>
<p>If the target class has 10 more functions then, assuming you&apos;ll want to test each function in multiple scenarios, this Test class may end up with about 25-30 more such test cases, but there&apos;s no way to group them.<br>
Let me be more specific about what I want, I still want all those tests within a single file, because they cover a single class that I&apos;m testing, but I want to group all the test cases for a single function together, this way it&apos;s easy to find issues if something is broken.</p>
<p>If you&apos;re from web / JavaScript background, then you probably already know what I mean, and probably experienced it first hand. What I&apos;m talking about is grouping of test cases like it&apos;s done in <a href="https://jasmine.github.io/">Jasmine</a> or <a href="https://rspec.info/">RSpec</a> or even <a href="https://cucumber.netlify.app/docs/gherkin/reference/">Cucumber&apos;s Gherkin</a> for the matter. If you&apos;re not familiar with the above-mentioned test frameworks, you can refer to the cover image of this post to get an idea about how it&apos;ll look.<br><br>
Well, it&apos;s now possible in Android, thanks to JUnit5 and JetBrains&apos; <a href="https://www.spekframework.org/">Spek</a>.</p>
<p>I was first introduced to Spek about two years ago by my dear friend <a href="https://www.aditlal.dev/">Adit Lal</a> and using it for personal projects ever since. Let me be honest with you, writing test cases with Spek is pure joy, it provides you two different styles of DSL (more on it later), and you can use your preferred one to write and better organize your test cases. The catch, however, is setup. As you might already know, JUnit5 doesn&apos;t support Android (or vice-versa) out-of-the-box, and Spek being the JUnit5 test framework (for Kotlin/JVM), you first need to set up JUnit 5 in your project, following which you need to setup Spek.</p>
<p>Since Spek setup isn&apos;t a straightforward process and getting frustrated is pretty easy here, I&apos;ll first show here how to setup Spek and JUnit 5, before discussing on writing test cases with Spek. If you want to skip the setup part, you can directly jump <a href="#writingorganisedtestcaseswithspek">here</a></p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="settingupspekandjunit5inyourandroidproject">Setting up Spek and JUnit5 in your Android Project</h3>
<p>We&apos;ll be using <code>Spek 2.x</code>, and we&apos;ll need to install the official <strong>Spek Framework</strong> plugin for that. You can get it here: <a href="https://plugins.jetbrains.com/plugin/10915-spek-framework">https://plugins.jetbrains.com/plugin/10915-spek-framework</a>. Install it and then restart your IDE (Android Studio or IntelliJ IDEA). Below is a screenshot from <code>Android Studio -&gt; Preferences -&gt; Plugins</code> (for Mac) after installing the plugin.</p>
<!--kg-card-end: markdown--><figure class="kg-card kg-image-card"><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/Screenshot-2020-04-18-at-11.05.10-PM.png" class="kg-image" alt="Writing Unit Tests efficiently in Android with Spek" loading="lazy"></figure><!--kg-card-begin: markdown--><p>Once you&apos;ve installed and restarted the IDE, we can proceed towards configuring your project for Spek and JUnit5.<br>
First, we&apos;ll need to add JUnit5 and JaCoCo BuildScript dependencies and Spek Maven repo to your project level build.gradle file as shown below.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-groovy">// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
  ext.kotlin_version = &quot;1.3.72&quot;
  repositories {
    google()
    jcenter()
  }
  dependencies {
    classpath &quot;com.android.tools.build:gradle:4.0.0-beta04&quot;
    classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;
    classpath &quot;de.mannodermaus.gradle.plugins:android-junit5:$android_junit5_version&quot;
    classpath &quot;org.jacoco:org.jacoco.core:$jacoco_version&quot;
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

allprojects {
  repositories {
    google()
    jcenter()
    maven { url &quot;https://dl.bintray.com/spekframework/spek-dev&quot; }
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>I&apos;m using Kotlin version <code>1.3.72</code>, in <em>Android Studio 4 - Beta 4</em>. The versions of Junit5, JaCoCo, and Spek are specified in gradle.properties file as follows.</p>
<pre><code class="language-groovy">spek_version=2.1.0-alpha.0.14+a763c30
android_junit5_version=1.5.2.0
junit5_runner=0.2.2
jacoco_version=0.8.1
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Next, we&apos;ll move to <strong>app level build.gradle</strong> file.<br>
Apply the JaCoCo and JUnit5 plugin as shown below.</p>
<pre><code class="language-groovy">apply plugin: &apos;jacoco&apos;
apply plugin: &apos;de.mannodermaus.android-junit5&apos;
</code></pre>
<p>After that, we need to set up <code>InstrumentationRunner</code>, paste the following inside <code>defaultConfig</code>, inside your <code>android</code> block.</p>
<pre><code class="language-groovy">testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
testInstrumentationRunnerArgument &quot;runnerBuilder&quot;, &quot;de.mannodermaus.junit5.AndroidJUnit5Builder&quot;
</code></pre>
<p>Then to set up <code>Spek2</code> Test Engine and event logging, paste the following code inside <code>android</code> block.</p>
<pre><code class="language-groovy">testOptions {
  junitPlatform {
    filters {
      engines {
        include &apos;spek2&apos;
      }
    }
    jacocoOptions {
      // here goes all jacoco config, for example
      html.enabled = true
      xml.enabled = false
      csv.enabled = false
    }
  }
  unitTests.all {
    testLogging.events = [&quot;passed&quot;, &quot;skipped&quot;, &quot;failed&quot;]
  }
}
</code></pre>
<p>Almost done, we just need to add the dependencies now, copy and paste the following inside <code>dependencies</code> block.</p>
<pre><code class="language-groovy">//kotlin-stdlib-jdk8 required
implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version&quot;
// assertion
testImplementation &quot;org.jetbrains.kotlin:kotlin-test:$kotlin_version&quot;
// spek2
testImplementation &quot;org.spekframework.spek2:spek-dsl-jvm:$spek_version&quot;
testImplementation &quot;org.spekframework.spek2:spek-runner-junit5:$spek_version&quot;
testImplementation &quot;org.jetbrains.kotlin:kotlin-reflect:$kotlin_version&quot;
androidTestImplementation &apos;androidx.test.espresso:espresso-core:3.2.0&apos;
androidTestImplementation &apos;com.android.support.test:runner:1.0.2&apos;
androidTestImplementation &quot;de.mannodermaus.junit5:android-test-core:1.0.0&quot;
androidTestRuntimeOnly &quot;de.mannodermaus.junit5:android-test-runner:1.0.0&quot;
</code></pre>
<p>And we&apos;re all done.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h6 id="dontforgettoaddimplementationorgjetbrainskotlinkotlinstdlibjdk8kotlin_versioneventhoughyoumayhaveimplementationorgjetbrainskotlinkotlinstdlibkotlin_versionifyouskipthejdk8dependencyyoullencounterthefollowingissue">Don&apos;t forget to add <code>implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version&quot;</code>, even though you may have <code>implementation &quot;org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version&quot;</code>, if you skip the jdk8 dependency, you&apos;ll encounter the following issue</h6>
<!--kg-card-end: markdown--><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/spekframework/spek/issues/622"><div class="kg-bookmark-content"><div class="kg-bookmark-title">java.lang.ClassNotFoundException: kotlin.streams.jdk8.StreamsKt &#xB7; Issue #622 &#xB7; spekframework/spek</div><div class="kg-bookmark-description">I get java.lang.ClassNotFoundException: kotlin.streams.jdk8.StreamsKt when running Spek Framework plugin v2.0.0-IJ2018.3 in IntelliJ IDEA 2018.3.3 And my tests runs are green while they shouldn&amp;#39...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.githubassets.com/favicons/favicon.svg" alt="Writing Unit Tests efficiently in Android with Spek"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">spekframework</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://avatars2.githubusercontent.com/u/24952163?s=400&amp;v=4" alt="Writing Unit Tests efficiently in Android with Spek"></div></a></figure><!--kg-card-begin: markdown--><p>Also, you&apos;ll need to set target and source compatibility to jdk8, you can do that by pasting the following inside <code>android</code> block in your app level build.gradle.</p>
<pre><code class="language-groovy">compileOptions {
  sourceCompatibility JavaVersion.VERSION_1_8
  targetCompatibility JavaVersion.VERSION_1_8
}

kotlinOptions {
  jvmTarget = &apos;1.8&apos;
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="writingorganisedtestcaseswithspek">Writing Organised Test Cases with Spek</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, we&apos;re done setting up Spek, now it&apos;s time to write Tests, but what to test? I&apos;m not following TDD here, as that&apos;s an entire topic on its own. What I want to say is that I already have the code I want to write tests on, and it&apos;s the following</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-kotlin">package dev.rivu.mvijetpackcomposedemo.moviesearch.data.remote

//imports

class RemoteMovieDataStore(private val movieApi: MovieApi) : MovieDataStore {
    override fun getMoviesStream(searchQuery: String): Flowable&lt;List&lt;Movie&gt;&gt; {
        return Flowable.error(UnsupportedOperationException(&quot;Can&apos;t get stream from Remote&quot;))
    }

    override fun getMovies(searchQuery: String): Single&lt;List&lt;Movie&gt;&gt; {
        return movieApi.searchMovies(searchQuery)
            .map { movieResponse -&gt;
                movieResponse.movies
                    .map { movie -&gt;
                        Movie(
                            imdbID = movie.imdbID,
                            poster = movie.poster,
                            title = movie.title,
                            type = movie.type,
                            year = movie.year
                        )
                    }
            }
    }

    override fun addMovies(movieList: List&lt;Movie&gt;): Completable {
        return Completable.error(UnsupportedOperationException(&quot;Can&apos;t add to Remote&quot;))
    }

    override fun getMovieDetail(imdbId: String): Single&lt;MovieDetail&gt; {
        return movieApi.getMovieDetail(imdbId)
            .map {
                MovieDetail(
                    actors = it.actors.split(
                        &quot;, &quot;,
                        ignoreCase = true
                    ), // Jesse Eisenberg, Rooney Mara, Bryan Barter, Dustin Fitzsimons
                    awards = it.awards, // Won 3 Oscars. Another 171 wins &amp; 183 nominations.
                    boxOffice = it.boxOffice, // $96,400,000
                    country = it.country, // USA
                    dVD = it.dVD, // 11 Jan 2011
                    director = it.director, // David Fincher
                    genre = it.genre, // Biography, Drama
                    imdbID = it.imdbID, // tt1285016
                    imdbRating = it.imdbRating, // 7.7
                    imdbVotes = it.imdbVotes, // 590,040
                    language = it.language, // English, French
                    metascore = it.metascore, // 95
                    plot = it.plot, // As Harvard student Mark Zuckerberg creates the social networking site that would become known as Facebook, he is sued by the twins who claimed he stole their idea, and by the co-founder who was later squeezed out of the business.
                    poster = it.poster, // https://m.media-amazon.com/images/M/MV5BOGUyZDUxZjEtMmIzMC00MzlmLTg4MGItZWJmMzBhZjE0Mjc1XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg
                    production = it.production, // Columbia Pictures
                    rated = it.rated, // PG-13
                    ratings = it.ratings.map {
                        MovieDetail.Rating(
                            source = it.source,
                            value = it.value
                        )
                    },
                    released = it.released, // 01 Oct 2010
                    response = it.response, // True
                    runtime = it.runtime, // 120 min
                    title = it.title, // The Social Network
                    type = it.type, // movie
                    website = it.website, // N/A
                    writer = it.writer, // Aaron Sorkin (screenplay), Ben Mezrich (book)
                    year = it.year // 2010
                )
            }
    }

    override fun addMovieDetail(movie: MovieDetail): Completable {
        return Completable.error(UnsupportedOperationException(&quot;Can&apos;t add to Remote&quot;))
    }
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>It&apos;s basically the remote implementation of <code>DataStore</code> interface of a Movie Search app, it has a dependency, a <code>MovieApi</code> instance, `MovieApi here is a Retrofit API interface as follows (if you&apos;re unfamiliar with Retrofit then consider this as a simple interface).</p>
<pre><code class="language-kotlin">interface MovieApi {

    @GET(&quot;/&quot;)
    fun searchMovies(
        @Query(&quot;s&quot;) query: String,
        @Query(&quot;type&quot;) type: String = &quot;movie&quot;,
        @Query(&quot;apikey&quot;) apikey: String = BuildConfig.ApiKey
    ): Single&lt;MovieSearchResponse&gt;

    @GET(&quot;/&quot;)
    fun getMovieDetail(
        @Query(&quot;i&quot;) imdbId: String,
        @Query(&quot;apikey&quot;) apikey: String = BuildConfig.ApiKey
    ): Single&lt;MovieDetailResponse&gt;
}
</code></pre>
<p>And, here&apos;s the <code>DataStore</code> interface, that our <code>RemoteMovieDataStore</code> implements</p>
<pre><code class="language-kotlin">interface MovieDataStore {
    fun getMoviesStream(searchQuery: String): Flowable&lt;List&lt;Movie&gt;&gt;

    fun getMovies(searchQuery: String): Single&lt;List&lt;Movie&gt;&gt;

    fun addMovies(movieList: List&lt;Movie&gt;): Completable

    fun getMovieDetail(imdbId: String): Single&lt;MovieDetail&gt;

    fun addMovieDetail(movie: MovieDetail): Completable
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><p>So now as we have the code ready, let&apos;s get on with it and start writing test cases. As we already know, <code>RemoteMovieDataStore</code> depends on a `MovieApi` instance, so to write test cases for <code>RemoteMovieDataStore</code>, we either need to have a fake implementation of <code>MovieApi</code> or we need to mock it, here we are going to mock. A lot of developers are against mock, and to be honest, they&apos;re quite right, if you use mocking incorrectly it can become a pain, but it&apos;s a very useful tool as well. I completely agree with what Donn Felker said in this tweet chain below.<!--kg-card-end: html--><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://twitter.com/donnfelker/status/1248323955838025729"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Donn Felker on Twitter</div><div class="kg-bookmark-description">&#x201C;Mock objects are useful ... Mock libraries are useful ...Mocking during tests is useful ... ... when used the correct way. Don&#x2019;t accidentally get rid of something good just because it was used incorrectly (or you didn&#x2019;t understand it). Use it correctly, or don&#x2019;t use it.&#x201D;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://abs.twimg.com/icons/apple-touch-icon-192x192.png" alt="Writing Unit Tests efficiently in Android with Spek"><span class="kg-bookmark-author">Twitter</span><span class="kg-bookmark-publisher">donnfelker</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://pbs.twimg.com/profile_images/1159503090455916544/ga7jV_ii_400x400.jpg" alt="Writing Unit Tests efficiently in Android with Spek"></div></a></figure><!--kg-card-begin: markdown--></p><p>I&apos;ll be using <a href="https://site.mockito.org/">mockito</a> and <a href="https://github.com/nhaarman/mockito-kotlin">mockito-kotlin</a>, you can use <a href="https://mockk.io/">mockK</a> as well if you like that.</p>
<p>Just like usual JUnit tests, we will be writing our test cases inside the <code>test</code> directory of your module. So, go inside <code>test</code> directory, go on and create the same package structure as your target class (here <code>dev.rivu.mvijetpackcomposedemo.moviesearch.data.remote</code>), and then create a new <strong>Kotlin file</strong>, let&apos;s name it <code>RemoteMovieDataStoreSpecTest</code>.<br>
We will now declare a class of the same name inside the file and <code>extend</code> <code>Spek</code>, just like the below.</p>
<pre><code class="language-kotlin">class RemoteMovieDataStoreSpecTest : Spek({
    //test cases go here
})
</code></pre>
<p>Once you paste the above code in the file, you should be able to see a green arrow in your IDE, just like the ones you see in regular JUnit test cases, below is the screenshot for your reference.</p>
<!--kg-card-end: markdown--><figure class="kg-card kg-image-card"><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/Screenshot-2020-04-19-at-4.53.03-PM.png" class="kg-image" alt="Writing Unit Tests efficiently in Android with Spek" loading="lazy"></figure><!--kg-card-begin: markdown--><p>If you try and run the test cases now, it should fail with a message like <code>test framework quit unexpectedly</code>.<br>
Now, before writing the tests, we need to create the mock as well as an instance of the target class, right? Creating mock is same as before, just paste the following inside the curly braces.</p>
<pre><code class="language-kotlin">val movieApi: MovieApi = mock()
</code></pre>
<p>I kept it as <code>val</code> and outside of any initialization block because I want to create the mock instance once, and I believe, it&apos;s not really necessary to create a new mock instance for every single test, rather we can use <code>whenever(..).thenReturn(..)</code> for stubbing differently for each scenario or test case as we deem right.<br>
Now since the mock dependency is ready, let&apos;s create the target class (<code>RemoteMovieDataStore</code>) instance. Generally, in JUnit4, we create the target class instance inside a function annotated with <code>@Before</code> which is called before each of the functions with <code>@Test</code> annotation is called. Most of the time, we use that function solely for variable initialization. With Spek, if you don&apos;t need a setup block solely for initializing variables, Spek provides you with a delegation called <code>memoized</code>, it works pretty much like <code>lazy</code> delegate in Kotlin, only that instead of initializing the variable first time it&apos;s used like lazy, a memoized variable will be initialized before running each of the test-cases in the group where the variable is declared. However, you might still want a setup block, for example, when you want to setup RxJava with your <code>TestScheduler</code> or more precisely when you want to set up something using <code>RxJavaPlugins</code>, or to start observing to LiveData, etc., for those scenarios, you can use <code>beforeEachTest</code> in Spek, it works all the same like <code>@Before</code>, within the block/group you defined it.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Now, for writing the test cases, we need to choose which DSL style to use.  As I said earlier, Spek offers two styles of DSL for writing test cases, namely <a href="https://www.spekframework.org/specification/">Specification</a> which is also used in Jasmine and RSpec (also known as <code>describe -&gt; context -&gt; it</code> and <a href="https://www.spekframework.org/gherkin/">Gherkin</a>. You can use either/both of them, however, I strongly suggest don&apos;t mix them in a single project, rather use only one style throughout a project, for different projects you can use different ones. I&apos;ll be discussing both of them here, basically, I&apos;ll write the same tests using both the styles and you can decide for yourselves which one works for you better. First, we&apos;ll see the Specification style, I personally like this style better.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h4 id="usingspecificationstyleinspektowritetestcases">Using Specification style in Spek to write test cases</h4>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>The first test I&apos;ll be writing is for the function <code>getMovies</code> as you can see in the implementation above, it expects a <code>query</code>, will call <code>searchMovies</code> method from <code>MovieApi</code>, map the response object to data layer model class, and will pass on downstream. If there&apos;s a network error or if the <code>Single</code> returned from <code>searchMovies</code> method emits an error, it should also emit the same error.<br>
So, there are 2 scenarios here as below</p>
<ol>
<li><code>movieApi.searchMovies</code> emits error</li>
<li><code>movieApi.searchMovies</code> emits data</li>
</ol>
<p>Below is the group of test cases I wrote respecting both the scenarios.</p>
<pre><code class="language-kotlin">describe(&quot;#${RemoteMovieDataStore::getMovies.name}&quot;) {

    context(&quot;movieApi emits error&quot;) {

        val error = Exception(&quot;some error&quot;)

        beforeEachGroup {
            whenever(
                movieApi.searchMovies(
                    query = anyString(),
                    type = anyString(),
                    apikey = anyString()
                )
            )
                .thenReturn(
                    Single.error(error)
                )
        }

        it(&quot;should emit the same error, wrapped in Single&quot;) {
            val testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
            testObserver.assertError(error)
        }
    }

    context(&quot;movieApi emits data&quot;) {

        val dummyResponse = dummyMovieSearchResponse

        val dummyMovieList = dummyResponse.movies.map {
            Movie(
                imdbID = it.imdbID,
                poster = it.poster,
                title = it.title,
                type = it.type,
                year = it.year
            )
        }

        beforeEachGroup {
            whenever(
                movieApi.searchMovies(
                    query = anyString(),
                    type = anyString(),
                    apikey = anyString()
                )
            )
                .thenReturn(
                    Single.just(dummyResponse)
                )
        }

        it(&quot;should return the same error, wrapped in Single&quot;) {
            val testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
            testObserver.assertValue(dummyMovieList)
        }
    }
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p><code>describe</code> is the group that contains all the test cases for the method <code>getMovies</code>, inside <code>describe</code> there are two sub-groups I defined with <code>context</code>, in the first subgroup, we tested the error scenario, and in the second subgroup, we tested the success scenario.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, to break it down, <code>describe</code> and <code>context</code> is for grouping and/or subgrouping of test cases, and we can perform assertions inside <code>it</code>. However, I&apos;d like to note here that it&apos;s not mandatory to have <code>context</code> inside <code>describe</code>, you can directly have <code>it</code> block inside your <code>describe</code> block and perform assertions, if you feel you don&apos;t need a <code>context</code> blog, I&apos;ve done it for some methods as well, where there are no multiple scenarios to test.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Below is the whole <code>RemoteMovieDataStoreSpecTest</code> (with test cases for all the methods in <code>RemoteMovieDataStore</code>) for your reference.</p>
<pre><code class="language-kotlin">package dev.rivu.mvijetpackcomposedemo.moviesearch.data.remote

import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import dev.rivu.mvijetpackcomposedemo.moviesearch.data.datafactory.dummyMovieDetail
import dev.rivu.mvijetpackcomposedemo.moviesearch.data.datafactory.dummyMovieDetailResponse
import dev.rivu.mvijetpackcomposedemo.moviesearch.data.datafactory.dummyMovieSearchResponse
import dev.rivu.mvijetpackcomposedemo.moviesearch.data.model.Movie
import io.reactivex.rxjava3.core.Single
import org.mockito.ArgumentMatchers.anyString
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe


class RemoteMovieDataStoreSpecTest : Spek({

    val movieApi: MovieApi = mock()
    val remoteDataStore by memoized { RemoteMovieDataStore(movieApi) }

    describe(&quot;#${RemoteMovieDataStore::getMoviesStream.name}&quot;) {

        it(&quot;should return Flowable.error with UnsupportedOperationException&quot;) {
            val testObserver = remoteDataStore.getMoviesStream(&quot;&quot;).test()
            testObserver.assertError(UnsupportedOperationException::class.java)
        }
    }

    describe(&quot;#${RemoteMovieDataStore::addMovies.name}&quot;) {

        it(&quot;should return Completable.error with UnsupportedOperationException&quot;) {
            val testObserver = remoteDataStore.addMovies(listOf()).test()
            testObserver.assertError(UnsupportedOperationException::class.java)
        }
    }

    describe(&quot;#${RemoteMovieDataStore::addMovieDetail.name}&quot;) {

        it(&quot;should return Completable.error with UnsupportedOperationException&quot;) {
            val testObserver = remoteDataStore.addMovies(listOf()).test()
            testObserver.assertError(UnsupportedOperationException::class.java)
        }
    }

    describe(&quot;#${RemoteMovieDataStore::getMovies.name}&quot;) {

        context(&quot;movieApi emits error&quot;) {

            val error = Exception(&quot;some error&quot;)

            beforeEachGroup {
                whenever(
                    movieApi.searchMovies(
                        query = anyString(),
                        type = anyString(),
                        apikey = anyString()
                    )
                )
                    .thenReturn(
                        Single.error(error)
                    )
            }

            it(&quot;should emit the same error, wrapped in Single&quot;) {
                val testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
                testObserver.assertError(error)
            }
        }

        context(&quot;movieApi emits data&quot;) {

            val dummyResponse = dummyMovieSearchResponse

            val dummyMovieList = dummyResponse.movies.map {
                Movie(
                    imdbID = it.imdbID,
                    poster = it.poster,
                    title = it.title,
                    type = it.type,
                    year = it.year
                )
            }

            beforeEachGroup {
                whenever(
                    movieApi.searchMovies(
                        query = anyString(),
                        type = anyString(),
                        apikey = anyString()
                    )
                )
                    .thenReturn(
                        Single.just(dummyResponse)
                    )
            }

            it(&quot;should return the same error, wrapped in Single&quot;) {
                val testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
                testObserver.assertValue(dummyMovieList)
            }
        }
    }

    describe(&quot;#${RemoteMovieDataStore::getMovieDetail.name}&quot;) {

        context(&quot;movieApi returns error&quot;) {

            val error = Exception(&quot;some error&quot;)

            beforeEachGroup {
                whenever(movieApi.getMovieDetail(imdbId = anyString(), apikey = anyString()))
                    .thenReturn(
                        Single.error(error)
                    )
            }

            it(&quot;should return the same error, wrapped in Single&quot;) {
                val testObserver = remoteDataStore.getMovieDetail(&quot;&quot;).test()
                testObserver.assertError(error)
            }
        }

        context(&quot;movieApi returns data&quot;) {

            val dummyResponse = dummyMovieDetailResponse

            val dummyMovieDetail = dummyMovieDetail

            beforeEachGroup {
                whenever(movieApi.getMovieDetail(imdbId = anyString(), apikey = anyString()))
                    .thenReturn(
                        Single.just(dummyResponse)
                    )
            }

            it(&quot;should return the same error, wrapped in Single&quot;) {
                val testObserver = remoteDataStore.getMovieDetail(&quot;&quot;).test()
                testObserver.assertValue(dummyMovieDetail)
            }
        }
    }
})
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h4 id="usinggherkinstyleinspektowritetestcases">Using Gherkin style in Spek to write test cases</h4>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, we already learned <em>Specification</em> style, now let&apos;s see the <em>Gherkin</em> style. We&apos;ll be refactoring the first test case we wrote into Gherkin style as follows.</p>
<pre><code class="language-kotlin">Feature(&quot;#${RemoteMovieDataStore::getMovies.name}&quot;) {

    Scenario(&quot;movieApi emits error&quot;) {

        val error = Exception(&quot;some error&quot;)

        beforeEachGroup {
            whenever(
                movieApi.searchMovies(
                    query = anyString(),
                    type = anyString(),
                    apikey = anyString()
                )
            )
                .thenReturn(
                    Single.error(error)
                )
        }

        lateinit var testObserver: TestObserver&lt;List&lt;Movie&gt;&gt;

        When(&quot;remoteDataStore.getMovies is called&quot;) {
            testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
        }

        Then(&quot;should emit the same error, wrapped in Single&quot;) {
            testObserver.assertError(error)
        }
    }

    Scenario(&quot;movieApi emits data&quot;) {

        val dummyResponse = dummyMovieSearchResponse

        val dummyMovieList = dummyResponse.movies.map {
            Movie(
                imdbID = it.imdbID,
                poster = it.poster,
                title = it.title,
                type = it.type,
                year = it.year
            )
        }

        beforeEachGroup {
            whenever(
                movieApi.searchMovies(
                    query = anyString(),
                    type = anyString(),
                    apikey = anyString()
                )
            )
                .thenReturn(
                    Single.just(dummyResponse)
                )
        }

        lateinit var testObserver: TestObserver&lt;List&lt;Movie&gt;&gt;

        When(&quot;remoteDataStore.getMovies is called&quot;) {
            testObserver = remoteDataStore.getMovies(&quot;&quot;).test()
        }

        Then(&quot;should emit the same data, mapped&quot;) {
            testObserver.assertValue(dummyMovieList)
        }
    }
}
</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, now we&apos;ve <code>Feature</code> instead of <code>describe</code>, <code>Scenario</code> instead of <code>context</code> and then we have an additional block <code>When</code>, inside where you need to perform the method call you&apos;re testing, then finally do the assertions in <code>Then</code>, if you have multiple assertions to perform for a given method call in a particular scenario, while using the <em>Specification</em> style we can have all of them inside <code>it</code>, but in <em>Gherkin</em> style it&apos;s recommended to have each of the assertions separately in <code>Then</code> blocks.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><h3 id="wrappingup">Wrapping Up</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, that&apos;s all about Spek, we have covered setup, initializations, and then we learned about two different DSL styles Spek offers for writing test cases. Hope you liked it. You can find them all inside this demo project I&apos;m building with Jetpack-Compose: <a href="https://github.com/RivuChk/Jetpack-Compose-MVI-Demo">https://github.com/RivuChk/Jetpack-Compose-MVI-Demo</a>, that project is still WIP.<br>
Please share your feedback/suggestions in the comments section</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Why You should focus more on Design Patterns than DS for Sr. / Lead Android interviews]]></title><description><![CDATA[Then how to check the candidate's skills properly? frameworks may change any day, there's only so much good questions you can ask in a framework]]></description><link>https://rivu.dev/design-patterns-in-android-interview-vs-data-structures/</link><guid isPermaLink="false">673f82cc0b613e001cb86a84</guid><category><![CDATA[Android]]></category><category><![CDATA[AndroidDev]]></category><category><![CDATA[Dev]]></category><category><![CDATA[Interview]]></category><category><![CDATA[Data Structures]]></category><category><![CDATA[DS]]></category><category><![CDATA[Design Patterns]]></category><category><![CDATA[Architecture]]></category><category><![CDATA[Architect]]></category><category><![CDATA[optimisation]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Sat, 18 Apr 2020 11:01:16 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/background-design-2017-2.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2020/04/background-design-2017-2.jpg" alt="Why You should focus more on Design Patterns than DS for Sr. / Lead Android interviews"><p>I&apos;m giving and taking interviews for a long time now (obviously giving interviews for a longer time than taking interviews), I gave interviews to a few big startups/companies (I now work at one of them &#x1F609;), I also took a lot of interviews (currently I&apos;m taking ~2 interviews every working day), I also talked to a few experts in Android domain I know personally about their interview experiences and a few of my friends who are regularly taking interviews (both in my organization and outside). So, I&apos;m gonna summarise them here to help you make a better-informed decision on your interview rounds/policies/technics.</p>
<p>Before starting, let&apos;s agree on something. We do interviews to check the following, not to test if they can be a successor of Alan Turing.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><ul>
<li>Is the candidate a good fit for the team culturally? (Mostly done in Bar Raiser / Management / HR rounds)</li>
<li>Are they good at communication? (again, mostly done in Bar Raiser / Management / HR rounds)</li>
<li>Is the candidate good / can be good at the Day to Day job they&apos;ll have to do here if selected? (Main purpose of Tech Rounds)</li>
</ul>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Now that we agreed on what we check for in the interviews, let us now focus on what exactly that day to day job is.</p>
<p>So, I&apos;m in the Software Development industry for almost a decade now, currently working as a Sr. Software Engineer (Android) at <a href="https://byjus.com/">BYJU&apos;S</a> <a href="https://www.forbes.com/sites/anuraghunathan/2019/09/02/how-byju-raveendran-built-a-5-5-billion-business-with-his-edtech-startup/#5d447bc01647">(India&apos;s biggest Ed-Tech startup)</a>.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>So, what do I do in my day to day job? Or, let&apos;s say, what do most of the Sr. Developers / Sr. Engineers in the Android domain do in their Day to Day job (let&apos;s talk about Product based companies/startups)?The answer is that we all develop features, sometimes we work alone in a feature, sometimes we with a team on a feature, sometimes we develop MVP (not Model-View-Presenter, Minimal Viable Product) apps, and sometimes we lead a small team of developers developing an MVP / Feature, and sometimes we fix bugs (yes, it&apos;s sometimes not most of the times, if you do proper Unit Testing).<br>
Now, when we write code, how much Data Structure do we need? Well obviously we do sorting and searching, so yes, we use Data Structure, but how much concise decision do we need to make that requires Data Structure knowledge? Confused with the question!?, let&apos;s put it the other way, what do we write when you&apos;re sorting a list? Mostly the below.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><pre><code class="language-kotlin">list.sortedBy {
    it.property
}</code></pre>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Same for search, we use the Language / Library / Framework defined algorithms for our tasks, we don&apos;t write those algorithms ourselves. Now what the regular optimizations we perform on your algorithms for which we believe we need DS rounds? The list is below</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><ul>
<li>Try to avoid nested loops</li>
<li>Instead of having multiple loops back to back, if things can be done in a single loop and that won&apos;t affect the cleanliness then use a single loop</li>
<li>Try to run a loop as much less as you can</li>
</ul>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Now, tell me how much DS knowledge do you need to make these decisions? You just need an understanding of what is Time Complexity, that&apos;s all you need to know. I&apos;m sure backend devs or developers working on System Programming does a lot more than these and really require high skills in DS. Also, in Android, if you&apos;re building something like <a href="https://github.com/square/leakcanary">LeakCanary</a> or if your day to day work includes working extensively in Annotation processors / Compiler optimizations, I can understand you need really good Data Structure skills, this also explains why companies like Microsoft / Google needs to have extensive DS rounds.</p>
<p>But, if the job role of the candidate is to work on an Android app, no matter how big/complex the project is, you don&apos;t need much Data Structure knowledge, you just need a regular understanding of Time Complexities and how to optimize them.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><p>A popular argument I hear when I present the above logic is, then how to check the candidate&apos;s skills properly, frameworks may change any day and for good programmers, it&apos;s easy to pick up any framework. Another opinion is there are only so many good questions you can ask in a framework, also asking a well-experienced candidate to explain the difference between Activity and Fragment is not a good choice either. The thing is I&apos;ll not oppose these arguments, rather I agree to all these arguments totally, I&apos;m here to give an opinion that will answer to these arguments / give a better alternative. Here comes the second and crucial part of this blog - Design Patterns.<br>
Now, let&apos;s re-run the exercise. What do we do in our day to day work? we develop features, sometimes we work alone in a feature, sometimes we with a team on a feature, sometimes we develop MVP (Minimal Viable Product) apps, and sometimes we lead a small team of developers developing an MVP / Feature, and sometimes we fix bugs, sometimes we also refactor / re-architecture old codebase.<br>
So, let&apos;s say you&apos;re building an MVP (Minimal Viable Product), while coding, you need to move faster, you can&apos;t spend a huge time on discussing and deciding the architecture, but you also need to keep future scope in mind, i.e. in near future, it might be taken forward as a product, and then you&apos;d want to re-use what you&apos;re building now, rather than writing everything from scratch. To do that you need to be very good about Architectures / Architecture patterns.<br>
Forget about choosing Architecture for MVP or for feature, or even refactoring old codebase, we don&apos;t get that opportunity every day, that&apos;s actually our dream work right. But there are few decisions we make every day, below is a non-exclusive list.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><ul>
<li>Should we use Dagger or Koin for this project?</li>
<li>Should this class be Singleton?</li>
<li>Should I use <code>@Singleton</code> annotation for this dependency or <code>@FeatureScope</code>?</li>
<li>Should I create an interface for this class?</li>
<li>Should I use Mocking / Faking for this test?</li>
<li>Should I create a new callback interface or add a method to the existing one?</li>
</ul>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Now think what knowledge/skill we use most to make those decisions every day? Is that Data Structures? No, DS is no way related to this. This is nothing else but Design Patterns. I&apos;m not saying if you know Design Patterns you&apos;ll never need to have discussions before making those decisions, but Design Patterns / Design Principle knowledge will help you immensely take a logical decision. Not for the above-mentioned list of decisions, but Design Principles / Design Patterns are required for numerous day to day Programming jobs, irrespective of platform.</p>
<p>I recently gave an online talk about Android Architecture Patterns, there as well, I started with discussing SOLID principles, because of their close relation with every Architecture Pattern. If you look close enough to any Architecture / Architecture pattern, you will find most of the part if that architecture is inspired by some Design Pattern.</p>
<!--kg-card-end: markdown--><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.youtube.com/watch?v=h6g0T7CQbcY"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Dive into Android Architectures</div><div class="kg-bookmark-description">https://speakerdeck.com/rivuchk/arch-patterns-in-android</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.youtube.com/yts/img/favicon_144-vfliLAfaB.png" alt="Why You should focus more on Design Patterns than DS for Sr. / Lead Android interviews"><span class="kg-bookmark-author">YouTube</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://i.ytimg.com/vi/h6g0T7CQbcY/hqdefault.jpg" alt="Why You should focus more on Design Patterns than DS for Sr. / Lead Android interviews"></div></a></figure><!--kg-card-begin: markdown--><p>So, to answer the arguments we started this part with, we can replace Data Structure rounds with intensive Design Pattern rounds, so that we don&apos;t have to depend only on the frameworks for evaluating the candidate if a person is good with Design Pattern, they&apos;re generally good with programming as a whole and should be able to keep pace with changes in framework or pickup another framework if it needs to be. Just like in DS round, you can come up with complex custom made problems to test DS skills of a candidate, in Design Pattern rounds as well, you can give a problem to the candidate and let the candidate solve that using Design Pattern knowledge/skills, this way you&apos;ll subtly evaluate the analyzing / problem-solving skills of the candidate as well.<br>
Another thing you can do (a lot of startups are already doing this), is give the candidates an assignment, to develop an app over a given problem statement (for example ask them to build an app to show a list of Trending Repositories from GitHub), also if the candidate already has some interesting project and willing to share, you can consider evaluating that as well. Do this before any of the interview rounds, that way you can evaluate candidate&apos;s Android skills firsthand and save both the panel&apos;s and candidate&apos;s time as well.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><p>I would like to mention here something I noticed lately while taking interviews. Most of the candidates say they follow MVVM, LiveData, etc. because Google recommends them. That&apos;s great right, earlier there were very few who were even interested in Architectures right? No, if you go a bit deeper and ask them questions on not how to set up your project with MVVM, but how they work or theory behind a component of the said Architecture, most of the candidates get stuck there. I believe that&apos;s not a result of not-updating yourself, but rather a result of not giving care to the basics - Design Patterns, once you understand Design Patterns properly, it&apos;ll be easier for you to get the theory behind every component of any Architecture.<br>
So, I&apos;d like to end this post requesting all my fellow developers/interviewers to set up a common practice to have Design Patterns, especially for senior roles. Can we agree? Let me know in the comments section.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Writing Android UI Code in Jetpack Compose]]></title><description><![CDATA[<!--kg-card-begin: markdown--><h6 id="notethisarticlewaspublishedbackinmay2019justafterjetpackcomposegotannouncedingoogleioalotchangedsincethenincludingalltheapisdiscussedhereandyounolongerneedtoforkaospjusttousecompose">Note: This article was published back in May, 2019, just after Jetpack Compose got announced in Google IO. A lot changed since then, including all the APIs discussed here. And you no longer need to fork AOSP, just to use Compose.</h6>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>During Google IO 2019, The Android team announced <a href="https://developer.android.com/jetpack/compose/"><strong>Jetpack</strong></a></p>]]></description><link>https://rivu.dev/writing-android-ui-code-in-jetpack-compose/</link><guid isPermaLink="false">673f82cc0b613e001cb86a82</guid><category><![CDATA[Android]]></category><category><![CDATA[AndroidDev]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[FP]]></category><category><![CDATA[jetpack]]></category><category><![CDATA[compose]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[composable]]></category><category><![CDATA[UI]]></category><category><![CDATA[jetpack compose]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Mon, 13 May 2019 08:39:35 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2019/05/compose.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><h6 id="notethisarticlewaspublishedbackinmay2019justafterjetpackcomposegotannouncedingoogleioalotchangedsincethenincludingalltheapisdiscussedhereandyounolongerneedtoforkaospjusttousecompose">Note: This article was published back in May, 2019, just after Jetpack Compose got announced in Google IO. A lot changed since then, including all the APIs discussed here. And you no longer need to fork AOSP, just to use Compose.</h6>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2019/05/compose.jpg" alt="Writing Android UI Code in Jetpack Compose"><p>During Google IO 2019, The Android team announced <a href="https://developer.android.com/jetpack/compose/"><strong>Jetpack Compose</strong></a>, a Kotlin based, unbundled UI toolkit for writing declarative/reactive/functional UI code.</p>
<p>Now, what do we mean by saying <em>declarative/reactive/functional UI code</em>? Instead of writing tough to read, bloated XML files for UI and invoking them with id/tag in Java/Kotlin code, we will be writing self explanatory UI code in Java/Kotlin files itself in Reactive/Functional Programming Style, along with the behavior.</p>
<p><strong>Jetpack Compose isn&apos;t yet ready for production, not even in Alpha / Beta, it&apos;s in development and if you want to check it out you need to fork the AOSP project, and need to use a special Android Studio.</strong></p>
<p>So, why do we care to check it now? Why not wait for it being atleast in Alpha? The answer is <strong>Jetpack Compose</strong> will disrupt the way we presently structure code and build architecture, we will need to think in different ways since we will no longer be able to get view instance and will not be able to update UI based on Async operations in current ways, we have to follow different approaches. Gues what, we got sufficient time in our hand to figure out how to structure our code and architecture around Jetpack Compose, before it goes production ready, but in order to do so, <strong>we first need to understand how Jetpack Compose works, how to apply themes / styles, how to maintain state, and how to update view states based on async operations / network response, which we will be discussing in this series</strong>, so that once we get strong grips on Jetpack Compose, we can start thinking on architectures and code patterns.</p>
<p>For detailed instructions on how to fork AOSP and setup Android Studio, please visit: <a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/ui/README.md">https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/ui/README.md</a></p>
<p>So, you are interested in Jetpack Compose and already set up everything, what more are we waiting for? Let&apos;s get started.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><h1 id="thecomposablefunctions">The @Composable functions</h1>
<p>The API is literally named after it, <strong>Composable</strong> functions are building blocks / smallest units of building UI in Jetpack Compose.<br>
Yes, you read it right, say goodbye to creating numbers of Classes and XML Layout files and attribute-sets.</p>
<p>You just need to write simple Kotlin functions, returning <code>Unit</code>, to design your UI and annotate them with <code>@Composable</code>, withing this function, you can use <em>pre-existing</em> <code>@Composable</code> functions like DSL, these <em>pre-existing</em> composable functions can be again created by you or can be shipped with Jetpack Compose API, or any other plugin/library for that matter.</p>
<p>For instance, take the below example.</p>
<pre><code class="language-kotlin">@Composable
fun Buttons(onClick: ()-&gt;Unit) {
    Button(onClick = onClick, text = &quot;Button 1&quot;)
    Button(onClick = onClick, text = &quot;Button 2&quot;)
}
</code></pre>
<p>This is a Composable function, which in turn calls another Composable function - <code>Button</code> (from package <code>androidx.ui.material</code>) twice to display two buttons in the screen.<br>
I can now write another composable function as follows and call the <code>Buttons</code> function.</p>
<pre><code class="language-kotlin">@Composable
fun ButtonsDemo(onClick: () -&gt; Unit) {
    Text(text = &quot;Text 1&quot;)
    Buttons(onClick)
}
</code></pre>
<p>This Composable function <code>ButtonsDemo()</code> will display one text and two button components in the screen when called.</p>
<p>As you&apos;ve already noticed, the Composable functions can have parameters, based on your requirements, but are not expected to return any value.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><h1 id="setcontenttoactivity">Set Content to Activity</h1>
<p>So, we&apos;ve created composables based on our UI requirements, now it&apos;s time to display them inside the Activity.</p>
<p>While using XML, we call <code>setContentView(R.layout.layout_name)</code> or <code>setContentView(viewInstance)</code> to display a view instance / layout resource to the screen, with Jetpack Compose, we need to call <code>setContent</code> and pass a <code>@Composable</code> lambda to it, from where we can call the <code>@Composable</code> functions, like the below example.</p>
<pre><code class="language-kotlin">override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        Text(text= &quot;Hello World&quot;)
    }
}
</code></pre>
<p>Below is the definition of <code>setContent</code> extension function.</p>
<pre><code class="language-kotlin">fun Activity.setContent(composable: @Composable() () -&gt; Unit) =
    setContentView(FrameLayout(this).apply { compose(composable) })
</code></pre>
<p>It basically creates a <code>FrameLayout</code>, composes our <code>@Composable</code> lambda and thus all <code>@Composable</code> functions within it and draws it inside the <code>FrameLayout</code> for display.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><a id="crane_crash"></a><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>So, our Hello World application is done. Now, let us wrap the text in our custom Composable, as follows.</p>
<pre><code class="language-kotlin">class SimpleActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CustomText(text = &quot;Hello World&quot;)
        }
    }
}

@Composable fun CustomText(text: String) {
    Text(text = text, style = +themeTextStyle { h4 })
}
</code></pre>
<p>Should work like a charm, right? Wrong, as soon as you install the app and start the Activity, you&apos;ll get this crash: <a href="https://stackoverflow.com/q/56050892/4284706">https://stackoverflow.com/q/56050892/4284706</a>, workaround? You just need to put your composable inside a <code>CraneWrapper</code> and a Theme, just as follows.</p>
<pre><code class="language-kotlin">class SimpleActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CraneWrapper { 
                MaterialTheme { 
                    CustomText(text = &quot;Hello World&quot;)
                }
            }
        }
    }
}

@Composable fun CustomText(text: String) {
    Text(text = text, style = +themeTextStyle { h4 })
}
</code></pre>
<p>Run it now, and it&apos;ll work as expected.</p>
<p>Now, why does that happen? Why do we need the <code>CraneWrapper</code>? As said by <strong>Ragunath Jawahar</strong>, <strong>Romain Guy</strong> and <strong>Leland Richardson</strong> in <em>compose</em> channel of <em>Kotlinlang Slack</em>, the <code>CraneWrapper</code> is a Composable, that hosts the compose tree with help of <code>AndroidCraneview</code>grants access to the <code>Context</code>, <code>Density</code>, <code>FocusManager</code> and <code>TextInputService</code> implicitly to all of its children, without <code>CraneWrapper</code> the composables doesn&apos;t gets access to these resources thus throws exception causing your app to crash.</p>
<p><strong>Note</strong>: I believe (also hinted by the Google team working on Jetpack Compose), in future we will probably not need to use <code>CraneWrapper</code>, as they will fix this soon enough, by probably adding <code>CraneWrapper</code> inside <code>setContent {}</code> or otherwise.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><h1 id="styleityourway">Style it your way</h1>
<p>So, we created Hello World app and created+used our first custom <strong>Composable</strong>, now let&apos;s take one more step forward, how to define your own styles / text styles / theme? Let&apos;s figure it out together.</p>
<p>Generally, with our present structure, we define Themes and Styles in a XML file and keep it inside <code>styles</code> folder, and to use it we refer it from the manifest file (to set default theme for an Activity), and from Views in XML, to set a style to that particular view, sometimes we also call them from Java/Kotlin file and pass it to an instance of a view.</p>
<p>Defining and using styles/themes are easier with Jetpack Compose, more over a brilliant use of Kotlin receiver types ensure that the IDE suggest you available styles / textstyles when using them. In the last example, I used <code>MaterialTheme</code> (which comes along with the <code>ui-material</code> module of Compose) as the default theme for the activity, I also used <code>h4</code> from <code>MaterialTheme</code> and applied it to <code>Text</code> inside <code>CustomText</code>, as <code>CustomText</code> was used inside <code>MaterialTheme</code>, all the styles inside <code>MaterialTheme</code> became available to it, thanks to function composing, and then we just used the <code>h4</code> text style from it.</p>
<p>Enough of contexts, now let&apos;s get hands dirty and define our new Custom Theme.</p>
<pre><code class="language-kotlin">val primary = Color(0xFF021AEE.toInt())
val primaryText = Color(0xFFEE0290.toInt())
val secondary = Color(0xFFD602EE.toInt())
val white = Color(0xFF26282F.toInt())
val black = Color(0xFFFFFFFF.toInt())

@Composable
fun CustomTheme(@Children children: @Composable() () -&gt; Unit) {
    val colors = MaterialColors(
        primary = primary,
        secondary = secondary,
        surface = white,
        onSurface = black
    )
    val textStyles = MaterialTypography(
        h1 = TextStyle(fontFamily = FontFamily(&quot;RobotoCondensed&quot;),
            fontWeight = FontWeight.w100,
            color = primaryText,
            fontSize = 96f),
        h2 = TextStyle(fontFamily = FontFamily(&quot;RobotoCondensed&quot;),
            fontWeight = FontWeight.w100,
            color = primaryText,
            fontSize = 60f),
        h3 = TextStyle(fontFamily = FontFamily(&quot;Eczar&quot;),
            fontWeight = FontWeight.w500,
            color = primaryText,
            fontSize = 48f),
        h4 = TextStyle(fontFamily = FontFamily(&quot;RobotoCondensed&quot;),
            fontWeight = FontWeight.w700,
            color = primaryText,
            fontSize = 34f),
        h5 = TextStyle(fontFamily = FontFamily(&quot;RobotoCondensed&quot;),
            fontWeight = FontWeight.w700,
            color = primaryText,
            fontSize = 24f),
        h6 = TextStyle(fontFamily = FontFamily(&quot;RobotoCondensed&quot;),
            fontWeight = FontWeight.w700,
            color = primaryText,
            fontSize = 20f)
    )
    MaterialTheme(colors=colors, typography = textStyles) {
        val value = TextStyle(color = black) // set default textstyle when not specified
        CurrentTextStyleProvider(value = value) {
            children()
        }
    }
}
</code></pre>
<p>That&apos;s it, we created our own custom Theme, now in order to use it in the last example, we just need to make the below changes.</p>
<pre><code class="language-kotlin">class SimpleActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CraneWrapper {
                CustomTheme {
                    CustomText(text = &quot;Hello World&quot;)
                }
            }
        }
    }
}

@Composable fun CustomText(text: String) {
    Text(text = text, style = +themeTextStyle { h4 })
}
</code></pre>
<p>That&apos;s right, we just need to call <code>CustomTheme</code> from the activity, instead of <code>MaterialTheme</code> and everything else will be taken care of.</p>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><h2 id="updatenoxmlsyntax">Update: No XML Syntax</h2>
<p>As Suggested by <strong>Romain Guy</strong> in the comments section, XML Syntax is going away, and we shouldn&apos;t use that with <strong>Jetpack Compose</strong>, so I updated all the code here with DSL syntax and asking all of you to not use the XML syntax, rather use it the way it is, a DSL.</p>
<p>While invoking <code>@Composable</code> functions, if you&apos;re getting compile time error saying: <strong>&quot;Stateless function shouldn&apos;t be invoked&quot;</strong> then, you need to add the below lines in module level <code>build.gradle</code> inside <code>android</code> block. <strong>This is a temporary workaroud, until the team ships a proper fix.</strong></p>
<pre><code class="language-kotlin">tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { compile -&gt;
    compile.kotlinOptions.freeCompilerArgs +=&quot;-P&quot;
    compile.kotlinOptions.freeCompilerArgs += &quot;plugin:androidx.compose.plugins.kotlin:syntax=FCS&quot;
}
</code></pre>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Basics of Functional Programming with Kotlin (1 of 3)]]></title><description><![CDATA[In this post, we'll discuss about how to get started with Functional Programming and it's underlying concepts using the  Kotlin Language.]]></description><link>https://rivu.dev/basics-of-functional-programming-with-kotlin/</link><guid isPermaLink="false">673f82cc0b613e001cb86a81</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[FP]]></category><category><![CDATA[Immutability]]></category><category><![CDATA[Pure Functions]]></category><category><![CDATA[Lambda]]></category><category><![CDATA[Functions]]></category><category><![CDATA[High Order]]></category><category><![CDATA[High Order Functions]]></category><category><![CDATA[Getting Started]]></category><category><![CDATA[immutable]]></category><dc:creator><![CDATA[Rivu Chakraborty]]></dc:creator><pubDate>Sun, 24 Mar 2019 19:55:19 GMT</pubDate><media:content url="https://s3-us-east-2.amazonaws.com/rivu.dev/2019/05/mathematical-functions.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://s3-us-east-2.amazonaws.com/rivu.dev/2019/05/mathematical-functions.jpg" alt="Basics of Functional Programming with Kotlin (1 of 3)"><p>So you&apos;re interested in functional programming and want to learn it, great. In case you are still confused about whether to use/learn functional programming or not and what benefits it&apos;ll serve to you / your performance overall, then let&apos;s get it sorted and get rid of your confusion first.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h2 id="why_functional_programming">Why Functional Programming?</h2><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>Every developer like me, who are from OOP background gets a FOMO (Fear to Move Out) to start on functional programming.<br>
If we want to describe the benefits of functional programming in one sentence then it&apos;ll say &quot;<strong>Functional Programming helps you write pragmatic, less error-prone and concurrency ready (without any extra effort) code</strong>&quot;.<br>
How? Let us start answering this by knowing what functional programming is.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h2 id="what_is_functional_programming">What is Functional Programming</h2><!--kg-card-end: html--><!--kg-card-begin: markdown--><blockquote>
<p>Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style.<br>
Credit - <a href="https://www.geeksforgeeks.org/functional-programming-paradigm/">https://www.geeksforgeeks.org/functional-programming-paradigm/</a></p>
</blockquote>
<p>Many people say functional programming is a replacement of Object Oriented Programming and they&apos;re very different. However, in my opinion, you can think of functional programming not as a replacement but as an evolution of OOP.<br>
Both FP and OOP rely on Abstraction and Polymorphism however instead of Inheritance in OOP, FP puts its bet on Composition (explained later in the series). Another big difference between OOP and FP is that in OOP we rely mostly on classes and properties of those classes, however, in functional programming having properties in classes other than <code>data</code> (POJO) classes (or in simpler words having global variables) is strongly discouraged, what is done instead is, we use more Pure Functions and Immutability and pass data from one function to another.<br>
The objective here is to stay as close to mathematics as possible.<br>
So, if you can consider functions similar to an immutable hashmap, where a particular parameter always makes the function return the same value and avoid state change, then the concurrency problem is automatically solved.</p>
<blockquote>
<p>Even if you don&apos;t want to follow FP, you can still use the four concepts below to make your program scalable.</p>
</blockquote>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h2 id="fp_concepts">FP Concepts</h2><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>Still here? That means you&apos;re now determined to learn Functional Programming, so let&apos;s get started.<br>
Every programming paradigm stands on top of few basic concepts, for example, to learn Object Oriented Programming (OOP), you&apos;ve to learn basic concepts underlying it such as Inheritance, Polymorphism, Abstraction etc. Similarly, to learn Functional Programming, you first need to learn four basic concepts of functional programming as listed below, please note that even if you don&apos;t want to follow FP, you can still use the four concepts below to make your program scalable.</p>
<ul>
<li>Immutability</li>
<li>Pure Functions</li>
<li>Lambda</li>
<li>High-Order Functions</li>
</ul>
<p>So lets with them.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h3 id="immutability">Immutability</h3><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>The concept of Immutability says, that a variable should return the exact same value when accessed at different times. This might sound similar to Constants, they are in fact similar to some extent, but it&apos;s not entirely the same.<br>
Let us take a look at below code to understand.</p>
<pre><code class="language-kotlin">data class MyData(val someValue1: String, val someValue2: String)

fun processUpdatedData(myData: MyData) {
    ....
}

val myData = MyData(&quot;V1&quot;, &quot;V2&quot;)
processUpdatedData(myData.copy(
    someValue2 = &quot;Updated value&quot;
))
</code></pre>
<p>In the above example, <code>myData</code> is an immutable variable, but when we need to use an updated value, we are using the <code>copy</code> constructor to get an updated instance of the <code>MyData</code> class, where the actual variable <code>myData</code> still holds the same value.<br>
In Java, the <code>String</code> class is immutable, but you can still modify a String variable, what is done here is that whenever you modify a String variable in Java, it internally uses the copy constructor, sets the updated value in a new instance of String, and updates the register (internal pointer) for your variable to point to the new location in memory where the updated instance resides. While the old value still resides in memory at its old place. Now, if you&apos;re thinking of memory efficiency, then let me tell you java did that to improve memory efficiency only. So every String variable in Java, which has the exact same value, resides in the same memory location, if you modify one variable among them, that particular variable will just start pointing to some other memory location with the updated value.<br>
So, that was about the concept of immutability and how Java used immutability to increase memory efficiency, how to implement them in your code in <strong>Kotlin</strong>? Let&apos;s find out.<br>
Unlike <strong>Java</strong>, Kotlin provides you easy ways to use immutability, and unlike other functional languages, Kotlin doesn&apos;t enforce immutability, but it encourages you to use Immutability.<br>
For your variable, you can use <code>val</code> instead of <code>var</code>, and <strong>please don&apos;t use any hacks to change the value of the <code>val</code> variable as you like</strong>, val just works like final variable in Java, it doesn&apos;t guaranty immutability, it&apos;s solely on the developers hand whether to respect immutability or not, as Kotlin uses getters and setters for variable access, a developer can always bypass immutability by using a custom getter, and please don&apos;t do that, please use a <code>var</code> instead of you really need such operations.<br>
<strong>Kotlin</strong> also provides support for immutable collections, in fact by default all collection objects are immutable (like <code>List</code>, <code>Map</code>, <code>Set</code> etc.), if you need to modify them after creation, you can use the mutable variant of these collections (eg. <code>MutableList</code>, <code>MutableSet</code>, <code>MutableMap</code> etc.).</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h3 id="pure_functions">Pure Functions</h3><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>The idea behind <strong>Pure Functions</strong> is that functions with their parameter should be cache-able, in order to get better performance, to achieve this, functions need to resemble their mathematical counterpart, that is, a function <em>f</em> should return the exact same value <em>y</em> when <em>x</em> is passed as parameter, in mathematical notation <code>f(x) = y</code> should always be true. Another important thing is a function shouldn&apos;t use/modify anything outside its scope.<br>
Let&apos;s take an example.</p>
<pre><code class="language-kotlin">fun power(number: Int, exponent: Int): Int {
    var result = 1
    if (exponent &lt; 0) {
        throw Exception(&quot;Negative value of exponent isn&apos;t supported, passed $exponent&quot;)
    }
    for(i in 1..exponent) {
        result = result * number
    }
    return result
}
</code></pre>
<p>In the above program, function <code>power()</code> would always return the same value for a given combination of <code>number</code> and <code>exponent</code> also, this function doesn&apos;t access or modify anything out of it&apos;s scope thus the <code>power()</code> is a <strong>Pure Function</strong>.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h4 id="side_effects">Side Effects</h4><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>When a function (presumed Pure Function) accesses or modifies anything out of it&apos;s scope, then that function is considered having <strong>Side Effects</strong>.<br>
For example if we add a log / <code>println</code> in the above function (the <code>power()</code> function), then it&apos;d not be Pure anymore and would be considered having <strong>Side Effects</strong>, and that log/<code>println</code> would be the said <strong>Side Effect</strong>.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html-->One important point to note here is that the `throw` statement that we used above is also a side-effect, how to remove that? We will be learning in the next post of this series with <a href="https://arrow-kt.io/" target="_blank">Arrow</a>.<!--kg-card-end: html--><!--kg-card-begin: html--><h3 id="lambda">Lambda</h3><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>Lambda are often referred as anonymous functions, Lambda (uppercase &#x39B;, lowercase &#x3BB;) is actually 11th letter in Greek alphabet and often used in mathematics to denote functions. That&apos;s where the term <strong>lambda</strong> came from into programming.<br>
So, what are they exactly? With lambda you can write a function like a mathematical expression, using a pair of curly braces and an arrow notation (<code>-&gt;</code>).<br>
Kotlin being a Functional Language, and treating Functions as it&apos;s first class citizen, gives you freedom to assign a lambda to a variable and even pass them to another function (that&apos;s where the <strong>High-Order Function</strong> comes into picture, discussed in the next section).<br>
Let&apos;s consider the below example.</p>
<pre><code class="language-kotlin">val power = {number: Int, exponent: Int -&gt;
    var result = 1
    if (exponent &lt; 0) {
        throw Exception(&quot;Negative value of exponent isn&apos;t supported, passed $exponent&quot;)
    }
    for(i in 1..exponent) {
        result = result * number
    }
    result
}

println(power(10,2))
println(power.invoke(10,3))
</code></pre>
<p>So, in the above example, the <code>power</code> is a variable as well as a function at a time, or it&apos;s better to say, that the power is a variable, which holds a function. The lambda, started and ended with the pair of curly braces, inside that, before the arrow notation (<code>-&gt;</code>), we provided the name and types of for the parameters, and the function body after <code>-&gt;</code>.<br>
The lambda returns the value last line, in this case it&apos;ll return the value of <code>result</code>.<br>
A lambda function can be invoked like an usual function or also by calling <code>invoke()</code>.<br>
To denote a variable would contain a lambda, you can use <code>(PARAMETERS)-&gt;RETURN_TYPE</code>, replacing <strong>PARAMETERS</strong> with list of parameters, and <strong>RETURN_TYPE</strong> with the return type of the function/lambda.<br>
So, as we learned a bit about Lambda, let&apos;s move towards it&apos;s close relative - <strong>High-Order Function</strong>.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h3 id="high_order_functions">High-Order Functions</h3><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>The name High-Order Function implies that these are functions which have higher order / higher class, than the usual functions. This is in fact to some extent correct. Those functions, which take other functions as parameter or returns another function are called <strong>High-Order Function</strong>, and here&apos;s where lies a strong coupling of <strong>Lambda</strong> and <strong>High-Order Function</strong>.<br>
Basically, High-Order Functions take Lambda(s) as parameter, or return a Lambda.<br>
Below are two examples of High-Order Functions.</p>
<pre><code class="language-kotlin">fun applyToNumberIfPositive(number: Int, lambda: (Int)-&gt;Int): Int {
    return if(number&gt;0) lambda(number) else number
}

fun getSquareFunction(): (Int)-&gt;Int {
    return {number -&gt;
        number*number
    }
}
</code></pre>
<p>The first one is a high-order function, which expects a lambda as parameter, whereas the second one is a high-order function which returns a high-order function.<br>
We can invoke them as follows.</p>
<pre><code class="language-kotlin">applyToNumberIfPositive(5, {
    number -&gt;
    number*2
})
getSquareFunction().invoke(2)
getSquareFunction()(4)
//We can also invoke them together.
applyToNumberIfPositive(10, getSquareFunction())
</code></pre>
<p>We could invoke both the High-Order functions together, as the <code>applyToNumberIfPositive</code> function expects a lambda with signature exactly same as the <code>getSquareFunction</code> function returns.<br>
Cool, isn&apos;t it?</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><h2 id="wrapping_up">Wrapping Up</h2><!--kg-card-end: html--><!--kg-card-begin: markdown--><p>So, in this post, we learned about basics of Functional Programming and it&apos;s underlying concepts, i.e. Immutability, Pure Functions, Side Effects, Lambda and High-Order Functions.<br>
Most important of all, we crossed FOMO to finally begin learning Functional Programming.<br>
But these are just beginning, to properly learn Functional Programming, one must also learn Typed FP and Category Theory, which are covered in the next post of this series.</p>
<!--kg-card-end: markdown--><!--kg-card-begin: html--><p style="font-style:bold,italic; font-weight:600; font-size:+1.5em; color:#3d828f;">In the next article of this series, we will discuss Typed FP and Category Theory and will see how to use <a href="https://arrow-kt.io/">Arrow</a> for Type FP in Kotlin</p><!--kg-card-end: html-->]]></content:encoded></item></channel></rss>