<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by lsivaranjan on Medium]]></title>
        <description><![CDATA[Stories by lsivaranjan on Medium]]></description>
        <link>https://medium.com/@lsivaranjan?source=rss-de1f0b308561------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ARV_qt_fWu7GA9hE</url>
            <title>Stories by lsivaranjan on Medium</title>
            <link>https://medium.com/@lsivaranjan?source=rss-de1f0b308561------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 06:06:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lsivaranjan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 3 - Loops And Conditions]]></title>
            <link>https://medium.com/@lsivaranjan/part-3-loops-and-conditions-902bf4528cab?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/902bf4528cab</guid>
            <category><![CDATA[golang-beginner]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-basics]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 03:50:57 GMT</pubDate>
            <atom:updated>2025-06-16T03:50:57.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O7-rU2RUUqwczcL5ZhPhA.png" /></figure><p>Now that we learnt arrays, let’s look into loops so this way we can loop an array as well.</p><h3><strong>Infinite Loops</strong></h3><p>We can iterate a infinite loop and repeat a function over n over again. This by the way is not recursive.</p><pre>func main() {<br>    var num = 0<br><br>    for {<br>       fmt.Println(num)<br>       num++<br>    }<br>}</pre><h3>For Each Loops</h3><p>Now let’s try and loop through an array and print the index and element on every iteration.</p><pre>func main() {<br>    names := []string{&quot;Batman&quot;, &quot;Superman&quot;, &quot;Green Lantern&quot;, &quot;Flash&quot;, &quot;Aquaman&quot;, &quot;Wonder Woman&quot;}<br><br>    for index, superHero := range names {<br>       fmt.Printf(&quot;Position is %d, Superhero Name is %s\n&quot;, index, superHero)<br>    }<br>}</pre><blockquote>Output</blockquote><blockquote>Position is 0, Superhero Name is Batman<br>Position is 1, Superhero Name is Superman<br>Position is 2, Superhero Name is Green Lantern<br>Position is 3, Superhero Name is Flash<br>Position is 4, Superhero Name is Aquaman<br>Position is 5, Superhero Name is Wonder Woman</blockquote><h3>If..Else</h3><p>This is going to be used almost everywhere in any application so let’s learn if else using our infinite loop,</p><pre>func main() {<br>    num := 1<br><br>    for {<br>       if num == 100 {<br>          break<br>       } else  {<br>          fmt.Printf(&quot;Number is %d&quot;, num)<br>          num++<br>       }<br>    }<br>}</pre><p>This will stop the infinite loop when the number hits 100.</p><h3><strong>For..If</strong></h3><p>Now, lets look into something wayyyy more intersting. Merging the For and If,</p><pre>func main() {<br>    num := 1<br><br>    for num &lt; 10 &amp;&amp; num &gt; 0 {<br>       fmt.Printf(&quot;Number is %d&quot;, num)<br>       num++<br>    }<br>}</pre><p>As you can see above, the for can also take conditions this way without us having to specify a dedicated if else block inside it.</p><h3>Switch</h3><p>let’s now look into switch which is actually very similar to other languages,</p><pre>func main() {<br>    city := &quot;Gotham&quot;<br><br>    switch city {<br>    case &quot;Gotham&quot;:<br>       fmt.Println(&quot;Batman is the Guardian&quot;)<br>    case &quot;Metropolis&quot;:<br>       fmt.Println(&quot;Superman is the Guardian&quot;)<br>    case &quot;Amazon&quot;:<br>       fmt.Println(&quot;Wonder Woman is the Guardian&quot;)<br>    }<br>}</pre><blockquote>Output</blockquote><blockquote>Batman is the Guardian</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902bf4528cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Go Lang With Me — Part 2]]></title>
            <link>https://medium.com/@lsivaranjan/learn-go-lang-with-me-part-2-8f98b987bb7e?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f98b987bb7e</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang-for-beginners]]></category>
            <category><![CDATA[golang-basics]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 20:54:52 GMT</pubDate>
            <atom:updated>2025-06-16T02:31:14.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2 - Arrays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O7-rU2RUUqwczcL5ZhPhA.png" /></figure><p><strong>Fixed Arrays</strong></p><p>In Go Lang, to create an array, We need to specify the length of the array on initialization of the variable itself. Here’s an Example,</p><pre>package main<br><br>func main() {<br>    var bookedCustomers [50]string<br>}</pre><p>The above variable allows up to 50 entries. Entries can be deleted, added or modified in it but not hold more than 50 entries at any point.</p><p>Now let’s see a detailed example on adding entries to that array,</p><pre>package main<br><br>func main() {<br>    var bookedCustomers [50]string<br>    bookedCustomers[0] = &quot;My First Entry&quot;<br>    bookedCustomers[1] = &quot;My Second Entry&quot;<br>    bookedCustomers[45] = &quot;My Third Entry&quot;<br>    bookedCustomers[52] = &quot;My Fourth Entry&quot;<br>}</pre><p>From the above example, I’ve added 4 entries,</p><ol><li>Entry on 0th position ~ This is valid entry as we know that our array allows entries up to 50.</li><li>Entry on 1st position ~ This is valid entry as well.</li><li>Entry on 45th position ~ This again is a valid entry and notice how I can choose any position to insert in the array which again is similar to what we see in other programming languages.</li><li>Entry on 52nd position ~ This is a invalid entry because our array can only support up to 50th position and this would throw a compilation error.</li></ol><p>Retrieving the entries from an array is very straightforward as well,</p><pre>func main() {<br>    var bookedCustomers [50]string<br>    bookedCustomers[0] = &quot;My First Entry&quot;<br>    bookedCustomers[1] = &quot;My Second Entry&quot;<br>    bookedCustomers[45] = &quot;My Third Entry&quot;<br>    <br>    fmt.Println(&quot;Every Entry in Array ~ &quot;, bookedCustomers)<br>    fmt.Println(&quot;Entry at position 1 ~ &quot;, bookedCustomers[1])<br>}</pre><blockquote>Output</blockquote><blockquote>Every Entry in Array ~ [My First Entry My Second Entry My Third Entry ]<br>Entry at position 1 ~ My Second Entry</blockquote><h3><strong>Dynamic Arrays - Slices</strong></h3><p>Now that we learnt about fixed arrays, What do we do in scenarios where we don’t know the size of an array ? Slices to the rescue !</p><p>Using Fixed Arrays in inefficient as the size is always constant and computing from that array is not really the best. On the other hand, the more efficient way to handle and use arrays is by using slices which expands and shrinks the array based off the number of entries added / removed. Here’s an example below,</p><pre>func main() {<br>    bookedCustomers := []string{}<br>    bookedCustomers = append(bookedCustomers, &quot;My First Entry&quot;)<br><br>    fmt.Println(&quot;Every Entry in Array ~ &quot;, bookedCustomers)<br>    fmt.Println(&quot;Length of Array is ~ &quot;, len(bookedCustomers))<br><br>    bookedCustomers = append(bookedCustomers, &quot;My Second Entry&quot;)<br><br>    fmt.Println(&quot;Every Entry in Array ~ &quot;, bookedCustomers)<br>    fmt.Println(&quot;Length of Array is ~ &quot;, len(bookedCustomers))<br>}</pre><blockquote>Output</blockquote><blockquote>Every Entry in Array ~ [My First Entry]<br>Length of Array is ~ 1<br>Every Entry in Array ~ [My First Entry My Second Entry]<br>Length of Array is ~ 2</blockquote><p>Now that we managed to add entries to the slice, We now need to be able to also delete entries. For this, we will use <strong>slices.Delete()</strong>,</p><pre>func main() {<br>    mNumbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}<br><br>    // Delete entry at position 1<br>    mNumbers = slices.Delete(mNumbers, 1, 2)<br><br>    fmt.Println(&quot;Every Entry in Array ~ &quot;, mNumbers)<br>    fmt.Println(&quot;Length of Array is ~ &quot;, len(mNumbers))<br>}</pre><blockquote>Output</blockquote><blockquote>Every Entry in Array ~ [1 3 4 5 6 7 8 9]<br>Length of Array is ~ 8</blockquote><p>slices.Delete() takes in the array as the first parameter, position to begin deletion as the second parameter and position to stop deletion as the third parameter. In the above example, the position to delete was 1 and position to stop deletion was 2 and hence only one entry was deleted.</p><p>Now let’s take a scenario where I want to delete all entries after 2nd position to 7th position. the element at position 2 is “3” and the element at position 7 is “8”, So we should see elements 3,4,5,6,7,8 disappear with the below snippet,</p><pre>func main() {<br>    mNumbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}<br><br>    mNumbers = slices.Delete(mNumbers, 2, 8)<br><br>    fmt.Println(&quot;Every Entry in Array ~ &quot;, mNumbers)<br>    fmt.Println(&quot;Length of Array is ~ &quot;, len(mNumbers))<br>}</pre><blockquote>Output</blockquote><blockquote>Every Entry in Array ~ [1 2 9]<br>Length of Array is ~ 3</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f98b987bb7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Go Lang With Me — Part 1]]></title>
            <link>https://medium.com/@lsivaranjan/learn-go-lang-with-me-part-1-d9f3f8bd348b?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f3f8bd348b</guid>
            <category><![CDATA[golang-for-beginners]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang-basics]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 05:17:33 GMT</pubDate>
            <atom:updated>2025-06-16T02:30:15.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 - Setup And Print</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O7-rU2RUUqwczcL5ZhPhA.png" /></figure><p>If you are interested in learning Go Lang step by step, then you are in the right place. I am not a professional at Go Lang. I am fluent with Android but this is my first dig at Go Lang. So I’m hoping this series helps more from the community to pick up Go Lang and start shipping Server Codes like a Pro !</p><ol><li>Download the Go Compile <a href="https://go.dev/doc/install"><strong>here</strong></a></li><li>Let’s download <a href="https://www.jetbrains.com/go/nextversion/"><strong>Go Land</strong></a><strong>.</strong></li><li>Once we have these 2 installed, go to terminal and type “go”. This should compile few things in terminal which is an indication that go compiler has been installed.</li></ol><p>Now that we have what we need, let’s open Go Land. Let’s create a sample project and upon creating the sample project we will see 2 files created.</p><ol><li>go.mod</li><li>main.go</li></ol><p>For the sake of relevance, i’m gonna speak and code only in main.go for now.</p><p>This “main.go” is the master file. Under here we have the function main() which will be used as the main starting point for running our code. here’s how it looks,</p><pre>package main<br><br>func main() {<br>    <br>}</pre><p>This function is now empty and there is nothing to run. So let’s start by doing the most basic thing, PRINT !! :D</p><p>go offers different ways to print but no matter what approach you take to print, you need to import “fmt” (format). This fmt allows us to handle format operations in Go. Let’s look at some examples now</p><pre>package main<br><br>func main() {<br>    fmt.Println(&quot;Hello World!\n&quot;)<br>    fmt.Printf(&quot;Hello World!&quot;)<br>}</pre><p>You would have noticed that I created two types of print statements here “Println” and “Printf”. We will get into the details of these very soon. Also you would have noticed we have “\n”. Weirdly in Go it does not automatically break the line when I print one after the other. Weird !!</p><p>Creating a variable in Go is very similar to kotlin. Others could find it different however, it is very easy. So let’s create a variable that holds like a First Name, Last Name and Age.</p><pre>package main<br><br>func main() {<br>    var firstName string = &quot;Lorem&quot;<br>    var lastName string = &quot;Ipsum&quot;<br>    var age uint = 28<br>    fmt.Println(&quot;First Name :&quot;, firstName, &quot;Last Name :&quot;, lastName, &quot;Age :&quot;, age)<br>}</pre><blockquote><strong>Output</strong></blockquote><blockquote>First Name : Lorem Last Name : Ipsum Age : 28</blockquote><p>now what is “var” ? , it’s used to declare a variable that can change it’s value at any point (mutable).</p><p>Now there is another way we can declare variables by completely avoiding “var”, here’s a sample below that replaces var,</p><pre>package main<br><br>func main() {<br>    firstName := &quot;Lorem&quot;<br>    lastName := &quot;Ipsum&quot;<br>    age := 28<br>    fmt.Println(&quot;First Name :&quot;, firstName, &quot;Last Name :&quot;, lastName, &quot;Age :&quot;, age)<br>}</pre><blockquote><strong>Output</strong></blockquote><blockquote>First Name : Lorem Last Name : Ipsum Age : 28</blockquote><p>Here we now use “:=” which basically is the equivalent of var but we need to assign a value if do this unlike var which does not force us to initialize a value on declaration itself. My personal favourite is with defining the type.</p><p>Now as promised i’ll show you the Printf usage using the above example itself,</p><pre>package main<br><br>func main() {<br>    firstName := &quot;Lorem&quot;<br>    lastName := &quot;Ipsum&quot;<br>    age := 28<br>    fmt.Printf(&quot;First Name : %s, Last Name : %s, Age : %d&quot;, firstName, lastName, age)<br>}</pre><blockquote><strong>Output</strong></blockquote><blockquote>First Name : Lorem, Last Name : Ipsum, Age : 28</blockquote><p>This is very similar to how we dynamically append values to strings in Android. My personal favourite however is Println here.</p><p>To create a constant, simply just use the type as “const” instead of “var”. This ensures that value will never change and is final.</p><p>Now let’s look into “Scan”. This was pretty cool and interactive.</p><p>Instead of assigning the values for First Name, Last Name and Age, Let’s ask for user input and dynamically fetch it.</p><pre>func main() {<br>    var firstName string<br>    var lastName string<br>    var age uint<br>    fmt.Println(&quot;Enter your First Name&quot;)<br>    fmt.Scan(&amp;firstName)<br>    fmt.Println(&quot;Enter your Last Name&quot;)<br>    fmt.Scan(&amp;lastName)<br>    fmt.Println(&quot;Enter your Age&quot;)<br>    fmt.Scan(&amp;age)<br><br>    fmt.Printf(&quot;First Name : %s, Last Name : %s, Age : %d&quot;, firstName, lastName, age)<br>}</pre><blockquote>Output</blockquote><blockquote>Enter your First Name<br>Batman<br>Enter your Last Name<br>Superman<br>Enter your Age<br>35<br>First Name : Batman, Last Name : Superman, Age : 35</blockquote><p>This time on running the code, instead of printing right away, it is asking you to enter your first name, last name and age. Only after entering all the 3 values, the final print statement is executed.</p><p>Now let’s look into creating a very small scenario where we let a user book tickets. Here’s the sample,</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    const totalTickets = 50<br>    var ticketsRemaining uint = totalTickets<br>    fmt.Println(&quot;The total tickets available are&quot;, totalTickets)<br>    fmt.Printf(&quot;Remaining Tickers are %d \n&quot;, ticketsRemaining)<br><br>    var firstName string<br>    var lastName string<br>    var email string<br>    var ticketsCount uint<br><br>    fmt.Println(&quot;What is your first name?&quot;)<br>    fmt.Scan(&amp;firstName)<br><br>    fmt.Println(&quot;What is your last name?&quot;)<br>    fmt.Scan(&amp;lastName)<br><br>    fmt.Println(&quot;What is your email?&quot;)<br>    fmt.Scan(&amp;email)<br><br>    fmt.Println(&quot;How many tickets to purchase?&quot;)<br>    fmt.Scan(&amp;ticketsCount)<br><br>    ticketsRemaining = ticketsRemaining - ticketsCount<br><br>    fmt.Println(firstName, lastName, &quot;bought&quot;, ticketsCount, &quot;tickets and their email is&quot;, email)<br>    fmt.Printf(&quot;Remaining Tickers are %d \n&quot;, ticketsRemaining)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f3f8bd348b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go Clean (Android Edition) — Part 3]]></title>
            <link>https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-3-e256f50fc2db?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/e256f50fc2db</guid>
            <category><![CDATA[jetpack-compose-mvvm]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[state-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[clean-mvvm]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Sun, 11 May 2025 23:39:14 GMT</pubDate>
            <atom:updated>2025-05-11T23:39:14.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlD6hVnwq9IVJVsv5lPNBw.jpeg" /></figure><h3><a href="https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-2-ce0f7946ff09?source=your_stories_page--------------------------------------------">Let’s Go Clean (Android Edition) — Part </a>3</h3><p>Note : Please go through previous parts before diving deeper into this.</p><p>In this chapter, We will dive into ViewModels and Views. We now have our domain data supplying the required information to populate our views as well (previous parts).</p><h3><strong>ViewModel</strong></h3><p>What’s a ViewModel ? a ViewModel in a traditional MVVM would be your state holder and your logic container but that feels too much for just one class right ? In our architecture, our ViewModel is only a View State holder.</p><p>Many would say “reuse ViewModels”, I strongly recommend Tie your ViewModels to your Views.</p><p>Every Screen SHOULD have it’s own ViewModel to manage it’s state.</p><p>Infact, we would even be able to create Smart Components using this concept.</p><p>Let’s get to creating a basic ViewModel using Hilt here,</p><pre>@HiltViewModel<br>class MainScreenViewModel@Inject constructor(<br>    private val myUseCase: MyUseCase<br>): ViewModel() {<br><br>}</pre><h3><strong>Let’s Compose</strong></h3><p>In this exercise, we will use Jetpack Compose for View Construction and inject our ViewModel into a composable. For Dependency Injection, We use Hilt.</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier,<br>    viewModel: MainScreenViewModel = viewModel()<br>) {<br>    ...<br>}</pre><p>Now lets analyze the above code, It’s a simple composable we have created for our Main Screen. We have also injected the ViewModel that’s going to be tied to our Main Screen. These are the basic things but what’s wrong with this code ?</p><p>When exposing this composable outside, we have exposed our implementation and also gave the caller the ability to modify the ViewModel. Plus we cannot make our ViewModel internal to our module as well.</p><p>How do we solve this ? Simple, just follow the below pattern for all of your Screens,</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier<br>) {<br>    MainScreenImpl(<br>        modifier = modifier<br>    )<br>}<br><br>@Composable<br>private fun MainScreenImpl(<br>    modifier: Modifier = Modifier,<br>    viewModel: MainScreenViewModel = viewModel()<br>) {<br>    <br>}</pre><p>By doing the above, We can now have our ViewModels and Domain layers internal while exposing only a dumb composable outside. Plus, you also have the ability to make your Composable act like a functional interface where in future if the implementation changes, you can handle it internally without forcing caller to change any code from their end.</p><h3><strong>Mutable States</strong></h3><p>Now in our views, we need to introduce a observer pattern and when it comes to Compose, people tend to lean towards MutableState or MutableStateFlow mostly. Honestly, MutableStateFlow would be more advantageous but personally I prefer MutableState because I lean towards State based architecture which has several benefits plus mutable state is lifecycle aware for Jetpack Compose out of the box. Again, this is a choice you can make and it’s still possible to create a state based architecture with MutableStateFlow as well. Let’s look at some code,</p><pre>@HiltViewModel<br>class MainScreenViewModel@Inject constructor(<br>    private val myUseCase: MyUseCase<br>): ViewModel() {<br>    var myData: UiResult&lt;ScreenData&gt; by mutableStateOf(UiResult.Uninitialized)<br>        private set<br><br>    fun fetchScreenData() = viewModelScope.launch {<br>        myData = UiResult.Loading<br>        myUseCase().collect {<br>            myData =  when(it) {<br>                is ApiResult.Success -&gt; UiResult.Loaded(it.data)<br>                is ApiResult.Error -&gt; UiResult.Failed(it.errorMessage)<br>                }<br>            }<br>        }<br>}</pre><p>Now let’s break down the above code,</p><ol><li>I’ve created a observer (mutableState) of type UiResult&lt;ScreenData&gt;. The ScreenData is nothing but a data class that holds some data for our screen provided by our API. The UiResult is the key to our State Architecture.</li><li>The UiResult is a sealed class that holds several states like Loaded, Failed, Loading, Uninitialized, etc</li><li>Since compose is declarative, Every state is coupled to the appropriate composable defining what is seen for the emitted state.</li></ol><p>Let’s look at how Compose treats this data now,</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier<br>) {<br>    MainScreenImpl(<br>        modifier = modifier<br>    )<br>}<br><br>@Composable<br>private fun MainScreenImpl(<br>    modifier: Modifier = Modifier,<br>    viewModel: MainScreenViewModel = viewModel()<br>) {<br>    when(val state = viewModel.myData) {<br>            is UiResult.Loaded -&gt; RenderScreen(state.data)<br>            is UiResult.Loading -&gt; RenderFullSCreenLoading()<br>            is UiResult.Failed -&gt; RenderErrorScreen()<br>            else -&gt; Unit<br>        }<br>}</pre><p>From the above snippet, We can see that anytime myData takes a change to the state, the MainScreenImpl will recompose to reflect on the latest state and render the appropriate composable.</p><p>Don’t worry about lifeCycle capabilities here, Compose and MutableState are made for each other to handle things out of the box.</p><p>The Use of UiResult need not be just for a screen level data. It can be for any observer to provide a pure reactive pattern that follows a pure state based architecture in your application.</p><p>Another huge benefit of this approach is that we will have non null data being passed to every composable since each composable is tied to a state which holds the data needed for each of those composables.</p><h3><strong>Recompose !</strong></h3><p>Now that we saw state based architecture using mutableStates, We should address the cons of compose here as well.</p><p>Whenever, a observer changes it’s state, the entire Composable will recompose. Now let’s look at the below code,</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier<br>) {<br>    MainScreenImpl(<br>        modifier = modifier<br>    )<br>}<br><br>@Composable<br>private fun MainScreenImpl(<br>    modifier: Modifier = Modifier,<br>    viewModel: MainScreenViewModel = viewModel()<br>) {<br>    Column {<br>        when(viewModel.myData) {<br>            is UiResult.Loaded -&gt; Text(text = &quot;Response was a Success&quot;)<br>            is UiResult.Loading -&gt; Text(text = &quot;Response Loading&quot;)<br>            else -&gt; Text(text = &quot;Fetch Initiated&quot;)<br>        }<br>        Button(<br>            onClick = {  }<br>        ) {<br>            Text(text = &quot;Go To Next Screen&quot;)<br>        }<br>        Text(text = &quot;This Screen is a Demo&quot;)<br>    }<br>}</pre><p>The above code is gonna be extremely poor in performance because every time you switch a state that needs to alter the first Text, Every composable inside is going to recompose. This is bad because only the first Text element needs to recompose to show the updated status. Let’s fix this problem now,</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier<br>) {<br>    MainScreenImpl(<br>        modifier = modifier<br>    )<br>}<br><br>@Composable<br>private fun MainScreenImpl(<br>    modifier: Modifier = Modifier,<br>) {<br>    Column {<br>        ResponseStatus()<br>        Button(<br>            onClick = {  }<br>        ) {<br>            Text(text = &quot;Go To Next Screen&quot;)<br>        }<br>        Text(text = &quot;This Screen is a Demo&quot;)<br>    }<br>}<br><br>@Composable<br>private fun ResponseStatus(<br>    modifier: Modifier = Modifier,<br>    viewModel: MainScreenViewModel = viewModel()<br>) {<br>    when(viewModel.myData) {<br>            is UiResult.Loaded -&gt; Text(text = &quot;Response was a Success&quot;)<br>            is UiResult.Loading -&gt; Text(text = &quot;Response Loading&quot;)<br>            else -&gt; Text(text = &quot;Fetch Initiated&quot;)<br>        }<br>}</pre><p>With the above change, ResponseStatus will be the only composable that recomposes leaving the Button and other Text untouched. When implementing this practice on a large scale application, We will see tremendous benefits.</p><p>Do Comment on a UseCase / Scenario for me to demonstrate this architecture further and I will link up an article with the answer :) happy to learn from the community while doing so 🍻 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e256f50fc2db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go Clean (Android Edition) — Part 2]]></title>
            <link>https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-2-ce0f7946ff09?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce0f7946ff09</guid>
            <category><![CDATA[clean-mvvm]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[jetpack-compose-mvvm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 00:54:52 GMT</pubDate>
            <atom:updated>2025-03-31T01:00:11.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlD6hVnwq9IVJVsv5lPNBw.jpeg" /></figure><h3>Let’s Go Clean (Android Edition) — Part 2</h3><p><strong>Note : </strong>Please look into the <a href="https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-1-80688a6e4029">fetchApiResult()</a> construction before proceeding with this part</p><h3>What are UseCases ?</h3><p>Usecases are classes that operate on a specific logic. The construction of these usecases would mean night and day for your application as everything right from threading to separation of concerns lies in it. Without more storytelling lets get into it 😉</p><p>Let’s get our Repository and Api Interface classes ready for the usecases to use and the construction of these are extremely straightforward but will cover them in a future post as well.</p><pre>interface MyApiInterface {<br>    @GET(&quot;/posts&quot;)<br>    suspend fun getAllPosts(): Response&lt;List&lt;Post&gt;&gt;<br>}</pre><pre>class MyRepository @Inject constructor(<br>    private val apiInterface: MyApiInterface<br>) {<br>    suspend fun getAllPosts() = apiInterface.getAllPosts()<br>}</pre><p>For the purpose of this exercise, I’ve used Hilt Injection but please feel free to use what you like as that has no relevance to what we are exploring here.</p><pre>class GetPostsUseCase @Inject constructor(<br>    private val repository: MyRepository,<br>    @Named(&quot;Default&quot;) private val dispatcher: CoroutineDispatcher<br>) {<br>    ...<br>}</pre><p>That’s our first glance to our usecase. Things to note here are the naming of the UseCase and the injected parameters.</p><ol><li>Naming ~ Align UseCase name to what it’s doing. In this case, its fetching all Posts and hence <strong>GetPostsUseCase()</strong>.</li><li>repository ~ Need not bore you folks about what this is 😄</li><li>dispatcher ~ This is very important. We injected a default dispatcher. Normally people would tell you to make your API Calls on IO but here we are using default to communicate with API. Well let’s explore why.</li></ol><pre>class GetPostsUseCase @Inject constructor(<br>    private val repository: MyRepository,<br>    @Named(&quot;Default&quot;) private val dispatcher: CoroutineDispatcher<br>) {<br>    operator fun invoke() = getAllPosts()<br><br>    private fun getAllPosts() = fetchApiResult {<br>        repository.getAllPosts()<br>    }.flowOn(dispatcher)<br>}<br></pre><p>Now how clean does that look ? 😉</p><p>Why invoke() ? Honestly it’s just a personal preference as I am the kinda person who loves to NOT expose functions or data when not needed outside of that class.</p><p>our fetchApiResult() will take our action repository.getAllPosts() and execute that on a IO thread as we saw in the last post. Once completed, that method will return the data as Flow for us.</p><p>Preferably have your UseCase emit the data as Sealed Class (you could in this case have ApiResult with Success and Failure continue in the stream). This allows you to build an architecture where the format of the data coming from your domain layers are consistent and easy to pick up by any engineer.</p><p>Ok so why do we need a default dispatcher here then ? because we are technically just making an api call and transmitting that data to our ViewModel and back to View while the fetchApiResult() handles IO threading.</p><p>This is more of a practice to boost your performance as seen below,</p><pre>class GetPostsUseCase @Inject constructor(<br>    private val repository: MyRepository,<br>    @Named(&quot;Default&quot;) private val dispatcher: CoroutineDispatcher<br>) {<br>    operator fun invoke() = getAllPosts()<br><br>    private fun getAllPosts() = fetchApiResult {<br>        repository.getAllPosts()<br>    }.map {<br>        // Handle your business logic here and transmit the resulting data<br>    }.flowOn(dispatcher)<br>}</pre><p>Now when it comes into that map, our flow will switch to default dispatcher to handle our client logic. This will have little to no impact in most cases but when you form a collection of API calls in a screen with everything computing post an API fetch, you will notice a difference in your Profiler. Go ahead and try it out 😉</p><p>Now that we constructed our UseCase, let’s look into some Rules which I strongly recommend to be followed,</p><ol><li>A UseCase <strong>should never</strong> have, emit or hold <strong>UI</strong> <strong>elements</strong> in it.</li><li>A UseCase <strong>should</strong> <strong>always</strong> represent only <strong>ONE</strong> operation. If there is a case where the operation performed by the UseCase is dependent on another operation, Create another UseCase for it and have the naming clear. This might sound like it’s a lot of work but it pays well to have these separation of concerns.</li><li>A UseCase <strong>can have</strong> other UseCases injected into it. That being said, i’m more inclined personally to have multiple UseCases injected to our ViewModel and have the ViewModel make the decision. For Example, ViewModel makes use of <strong>GetPostsUseCases</strong> to fetch all Posts and on receiving the data, the ViewModel could send the data to another UseCase to have that computed.</li><li><strong>Do not </strong>pass <strong>callbacks</strong> from your View or ViewModel to UseCases.</li><li><strong>Do not</strong> create <strong>variables</strong> in your usecases to store data. Let your ViewModel worry about that.</li><li>A UseCase <strong>can have</strong> more than <strong>ONE</strong> repository injected but again I personally would map separate UseCases to handle such scenarios.</li></ol><p>In the next chapter, I will go through ViewModel and Views</p><p>I know the world is trending towards Jetpack Compose, So I will begin with Compose and post one for Non Compose as a follow up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce0f7946ff09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go Clean (Android Edition) — Part 1]]></title>
            <link>https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-1-80688a6e4029?source=rss-de1f0b308561------2</link>
            <guid isPermaLink="false">https://medium.com/p/80688a6e4029</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[clean-mvvm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[lsivaranjan]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 03:49:49 GMT</pubDate>
            <atom:updated>2025-03-31T00:55:39.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlD6hVnwq9IVJVsv5lPNBw.jpeg" /></figure><h3>Let’s Go Clean (Android Edition) — Part 1</h3><p>One of the most asked questions within every android developer is “How can we make our codebase cleaner” While I feel that is a great question to start with but definitely not the only question to linger with. Making our codebase cleaner does not guarantee Scalability, Thread Safety, etc. However everyone starts somewhere and most of us start at MVVM these days.</p><p>What is MVVM ? Model View ViewModel is what that stands for. Feels boring to hear that over n over right ? Well lets step this up a little further. Add “Clean” to it 😜</p><p>Well this is ironic because I just mentioned that don’t stay with “clean” question yet again say go “clean”. What if I told you, Clean here is not about keeping it just “clean” and opens a world of opportunities for you ? Well let’s explore it then.</p><p>The majority would expect me to go from the View Layer and construct all the way to the Domain. I’m sorry !! I prefer to ensure my domain is well constructed so my view is as dumb as possible to simply request and display. So lets start from our Domain here.</p><p>When we speak for Domain, The first thing that comes to our mind is API .. API .. API. This is crucial because this is needed everywhere. Lets try and construct our API fetching layer first because that’s the end of the tunnel for the domain layer.</p><pre>fun &lt;T: Any&gt; fetchApiResult(<br>    execute: suspend () -&gt; Response&lt;T&gt;<br>)</pre><p>In the above block we have created a function that accepts any type of data when executing the retrofit call (hence suspend). This block is gonna be the source for all of our usecases to use and fetch API Response. So lets get to constructing this to the best of our needs.</p><pre>fun &lt;T: Any&gt; fetchApiResult(<br>    execute: suspend () -&gt; Response&lt;T&gt;<br>) = flow { <br>    execute().let { result -&gt;<br>        if (result.isSuccessful) {<br>            // Lets Emit Success Data<br>        } else {<br>            // Lets Emit Failed Data<br>        }<br>    }<br>}</pre><p>I personally like flows so I am going with having the function return a flow stream however, you can choose how you want your return data to be and that’s the whole point of this exercise. <strong>Flexibility</strong> !!!</p><p>The above snippet is extremely straightforward and as you can see, It is going to return Success or Failure Data. Now Let’s add more conditions which are likely to happen … <strong>Errors</strong> !!!</p><pre>fun &lt;T: Any&gt; fetchApiResult(<br>    execute: suspend () -&gt; Response&lt;T&gt;<br>) = flow&lt;T&gt; {<br>    try {<br>        execute().let { result -&gt;<br>            if (result.isSuccessful) {<br>                // Lets Emit Success Data<br>            } else {<br>                // Lets Emit Failed Data<br>            }<br>        }<br>    } catch () {<br>        // Lets Emit the Exception<br>    } catch () {<br>        // Lets Emit the Exception<br>    } catch () {<br>        // Lets Emit the Exception<br>    }<br>}</pre><p>There could be several types of exceptions we can expect in this layer and we can open a catch block for all our anticipations to throw the relevant output from here.</p><p>Now It’s best we have some sort of standard in the output and I strongly advise to all my friends and teammates. Some would think standard is only applicable when working in a company or so but standard is to make your code more readable and allows you to follow a concise pattern so you know without having to confuse yourself or others around you about what that code is doing. So lets introduce a <strong>Sealed Class</strong> to carry our data in this stream 🎉 🎉</p><pre>sealed class ApiResult&lt;T: Any&gt; {<br>    data class Success&lt;T : Any&gt;(val data: T): ApiResult&lt;T&gt;()<br>    data class Error&lt;T : Any&gt;(val errorType: ErrorType, val errorMessage: String): ApiResult&lt;T&gt;()<br>}</pre><p>The sealed class accepts two types, Success and Error. Feel free to stock the kinda data you would require from these states.</p><pre>fun &lt;T: Any&gt; fetchApiResult(<br>    execute: suspend () -&gt; Response&lt;T&gt;<br>): Flow&lt;ApiResult&lt;T&gt;&gt; = flow&lt;ApiResult&lt;T&gt;&gt; {<br>    try {<br>        execute().let { result -&gt;<br>            if (result.isSuccessful) {<br>                val apiBody = result.body()<br>                if (apiBody != null) {<br>                    emit(ApiResult.Success(data = apiBody))<br>                } else {<br>                    emit(<br>                        ApiResult.Error(<br>                            errorType = ErrorType.Server,<br>                            errorMessage = &quot;Result was null&quot;<br>                        )<br>                    )<br>                }<br>            } else {<br>                emit(<br>                    ApiResult.Error(<br>                        errorType = ErrorType.Server,<br>                        errorMessage = result.message()<br>                    )<br>                )<br>            }<br>        }<br>    } catch (ioException: IOException) {<br>        emit(<br>            ApiResult.Error(<br>                errorType = ErrorType.IoException,<br>                errorMessage = ioException.message.toString()<br>            )<br>        )<br>    } catch (t: Throwable) {<br>        emit(<br>            ApiResult.Error(<br>                errorType = ErrorType.GeneralThrowable,<br>                errorMessage = t.message.toString()<br>            )<br>        )<br>    }<br>}</pre><p>Now that looks pretty clean right ? 😉</p><p>This block is gonna be your single stop to modify anything API related so that the callers are receiving the data needed to make decisions. That being said let’s add the final touch to make this block a lot more versatile.</p><pre>fun &lt;T: Any&gt; fetchApiResult(<br>    execute: suspend () -&gt; Response&lt;T&gt;<br>): Flow&lt;ApiResult&lt;T&gt;&gt; = flow&lt;ApiResult&lt;T&gt;&gt; {<br>    ...<br>    ...<br>}.flowOn(Dispatchers.IO)</pre><p>Now sit back and relax because no one in your team can ever make the mistake of running an API call in the main thread and lowering the standard of the application 🥂</p><p>In the next chapter, We will go into <a href="https://medium.com/@lsivaranjan/lets-go-clean-android-edition-part-2-ce0f7946ff09"><strong>UseCases</strong></a> and the usage of the <strong>fetchApiResult()</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80688a6e4029" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>