<?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 Sourabh Sharma on Medium]]></title>
        <description><![CDATA[Stories by Sourabh Sharma on Medium]]></description>
        <link>https://medium.com/@sourabhsharma_5073?source=rss-db15d01f4db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R3M96yFFWCvZAXwNmkkRZQ.jpeg</url>
            <title>Stories by Sourabh Sharma on Medium</title>
            <link>https://medium.com/@sourabhsharma_5073?source=rss-db15d01f4db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:24:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sourabhsharma_5073/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[Boring Android Series : Coroutine Scopes]]></title>
            <link>https://medium.com/@sourabhsharma_5073/boring-android-series-coroutine-scopes-2b727177e9c?source=rss-db15d01f4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b727177e9c</guid>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Sourabh Sharma]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 16:16:23 GMT</pubDate>
            <atom:updated>2023-07-22T16:16:23.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>Boring Android Series : Coroutine Scopes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCKGKWMalKqjVt3sij3OhQ.png" /></figure><p>Welcome back to the Boring Android Series! In this post, we’re going to talk about coroutine scopes. Coroutine scopes are a powerful tool that can help you to manage the lifetime of coroutines in your Kotlin code. They can help to prevent memory leaks and ensure that coroutines are properly cancelled when they are no longer needed.</p><ul><li><a href="https://medium.com/@sourabhsharma_5073/boring-android-series-kotlin-coroutine-8259adc11cc8">Boring Android Series : Kotlin Coroutine</a></li><li><a href="https://medium.com/@sourabhsharma_5073/boring-android-series-suspend-function-and-coroutine-builder-2e0bb2109833">Boring Android Series : Suspend Function and Coroutine builder</a></li></ul><p>In the previous post, we talked about the basics of coroutines. We learned that coroutines are a way to run code asynchronously, which can help to improve the performance and responsiveness of your app. We also learned about the different types of coroutines, such as suspending functions and coroutine builders.</p><p>In this post, we’re going to build on that foundation and learn about coroutine scopes. We’ll see how coroutine scopes can help us to manage the lifetime of coroutines and prevent memory leaks. We’ll also see how coroutine scopes can be used to improve the performance and reliability of our code.</p><p>So, without further ado, let’s get started!</p><p>Imagine you are a child playing in a park. The park has different areas or sections where you can play different games. Each area represents a “scope” in coroutines.</p><p>Now, let’s relate this to programming. In a program, you have different parts of code that perform different tasks. Each task can be associated with a specific coroutine scope. A coroutine scope defines the lifespan and boundaries of a coroutine, just like the different areas in the park.</p><p>Inside each area of the park, you have certain rules or limitations. For example, you may be allowed to play on the swings and the slide, but not in the sandbox. Similarly, a coroutine scope may have specific rules or limitations for the coroutines within it.</p><p>These rules help ensure that the coroutines behave properly and don’t cause issues. For example, a scope might define that all coroutines within it should be cancelled if the scope is cancelled. This helps with proper cleanup and avoiding memory leaks.</p><p>In Kotlin, a coroutine scope is a construct that defines the lifecycle of a coroutine. It is used to manage the lifetime of coroutines and to ensure that they are properly cancelled when they are no longer needed.</p><p>There are several different types of coroutine scopes in Kotlin, each with its own specific purpose. Some of the most common types of coroutine scopes include:</p><p><strong>GlobalScope</strong>: This is the default coroutine scope, and it has the widest scope of all the coroutine scopes. Tasks launched in the global scope will live as long as the application does.<br><strong>LifecycleScope</strong>: This coroutine scope is tied to the lifecycle of a specific component, such as an activity or a viewmodel. Tasks launched in a lifecycle scope will be cancelled when the component is destroyed.<br><strong>ViewModelScope</strong>: This coroutine scope is similar to a lifecycle scope, but it is specifically designed for use with viewmodels. Tasks launched in a viewmodel scope will be cancelled when the viewmodel is cleared.</p><p>Coroutine scopes can be nested, which means that you can create a coroutine scope within another coroutine scope. This allows you to create a hierarchy of coroutine scopes, which can be helpful for managing the lifetime of complex coroutines.</p><p>To use a coroutine scope, you first need to create an instance of the scope. You can then use the launch() or async() functions to launch coroutines within the scope. When you are finished with the scope, you should cancel it to release any resources that it is using.</p><p>Here is an example of how to use a coroutine scope:</p><pre>fun main() {<br> val scope = CoroutineScope(Dispatchers.IO)<br> scope.launch {<br> // Do some work in the scope.<br> }<br>// Cancel the scope when we are finished with it.<br> scope.cancel()<br>}</pre><p>This code will create a coroutine scope and launch a coroutine within the scope. The coroutine will be cancelled when the scope is cancelled.</p><p>Here are some of the practical ways to use coroutine scopes in your coding adventures:</p><p><strong>To manage the lifetime of coroutines </strong>:</p><p>Coroutine scopes can help you to manage the lifetime of coroutines by automatically cancelling them when they are no longer needed. This helps to prevent memory leaks and ensures that your app is always running efficiently.</p><p><strong>To improve the performance and reliability of your code</strong>:</p><p>Coroutine scopes can help you to improve the performance and reliability of your code by ensuring that coroutines are properly cancelled when they are no longer needed. This can help to prevent your app from crashing or becoming unresponsive.</p><p><strong>To implement structured concurrency</strong>:</p><p>Coroutine scopes can be used to implement structured concurrency, which is a way of writing concurrent code that is safe and predictable. Structured concurrency helps to ensure that coroutines are properly coordinated and that they do not interfere with each other.</p><p>In conclusion, coroutine scopes are a fundamental concept in asynchronous programming with coroutines. They provide a way to manage the lifecycle and cancellation of coroutines in a structured and controlled manner. By defining a scope, you can create a clear boundary for coroutines, making it easier to handle errors and manage resources efficiently.</p><p>Remember, coroutine scopes are not only about defining a lifespan; they also offer additional benefits. They allow you to control the concurrency level, especially when dealing with nested coroutines or parallel tasks. Additionally, coroutine scopes can help you organize your code, making it more readable and maintainable.</p><p>When working with coroutine scopes, always consider the appropriate scope for your use case. Choosing the right scope ensures that your coroutines are appropriately canceled and resources are released when they are no longer needed.</p><p>In summary, understanding coroutine scopes is crucial for writing efficient, responsive, and reliable asynchronous code. Embrace their power and leverage them wisely to build robust and scalable applications in the asynchronous world. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b727177e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boring Android Series : Suspend Function and Coroutine builder]]></title>
            <link>https://medium.com/@sourabhsharma_5073/boring-android-series-suspend-function-and-coroutine-builder-2e0bb2109833?source=rss-db15d01f4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0bb2109833</guid>
            <dc:creator><![CDATA[Sourabh Sharma]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 13:02:06 GMT</pubDate>
            <atom:updated>2023-07-18T13:02:06.368Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@sourabhsharma_5073/boring-android-series-kotlin-coroutine-8259adc11cc8?source=your_stories_page-------------------------------------">Boring Android Series : </a>Suspend Function and Coroutine builder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xq6ZzSrUYT89akhJGCBoA.png" /></figure><p>welcome back to the Boring Android Series 🚀🚀. In the previous post, we learned about the basics of coroutines. We saw how coroutines can help us to run code asynchronously, which can improve the performance and responsiveness of our apps. here is the <a href="https://medium.com/@sourabhsharma_5073/boring-android-series-kotlin-coroutine-8259adc11cc8">link</a> in case you missed it.</p><p>In this post we are going to learn different types of coroutines, such as suspending functions and coroutine builders .</p><p>There are two types of coroutines:</p><p><strong>Suspension functions</strong> : These are functions that can be paused and resumed at a later time. This is useful for tasks that can be interrupted, such as waiting for user input or receiving a network response.</p><p>Imagine you’re playing a game, and suddenly you need to take a break to think or wait for something to happen. That’s exactly what suspending functions do! They pause for a little while and let other tasks happen.</p><p>Here is an example of a suspending function:</p><pre>suspend fun downloadFile(url: String): ByteArray = withContext(Dispatchers.IO) {<br> val byteArrayOutputStream = ByteArrayOutputStream()<br> val connection = URL(url).openConnection()<br>// Open a stream to download the file<br> val inputStream: InputStream = connection.getInputStream()<br>// Read the file data into a byte array<br> val buffer = ByteArray(1024)<br> var bytesRead: Int<br> while (inputStream.read(buffer).also { bytesRead = it } != -1) {<br> byteArrayOutputStream.write(buffer, 0, bytesRead)<br> }<br>// Close the input stream and return the downloaded bytes<br> inputStream.close()<br> byteArrayOutputStream.toByteArray()<br>}</pre><p>This function can be paused and resumed at any time. For example, if the user receives a phone call while the file is downloading, the download can be paused and resumed after the phone call is finished.</p><p><strong>Coroutine builders </strong>: These are functions that can be used to create coroutines. They provide a way to control the flow of execution of a coroutine and to coordinate the execution of multiple coroutines.</p><p>Here is an example of a coroutine builder:</p><pre>val scope = CoroutineScope(Dispatchers.IO)<br>scope.launch {<br> val fileUrl = &quot;https://example.com/file.txt&quot;<br>// Start a new coroutine to download the file<br> val downloadedBytes = async { downloadFile(fileUrl) }<br>// Do other tasks while the file downloads in the background<br> println(&quot;Downloading file…&quot;)<br>// Simulate doing other tasks for a while<br> delay(2000)<br>// Wait for the file to finish downloading and get the result<br> val bytes = downloadedBytes.await()<br>// File download complete!<br> println(&quot;File download complete! Total bytes: ${bytes.size}&quot;)<br> …<br>}</pre><p>This code creates a coroutine scope and launches a coroutine within the scope. The coroutine will download the file in the background and then do something with the bytes of the file.</p><p>Imagine you’re building a tower with building blocks. Each block has special instructions written on it to help you build the tower in different ways. Similarly, coroutine builders provide us with special instructions to create and manage coroutines.</p><p>Here are a few coroutine builders that can help us:</p><ol><li>launch: This builder helps us start a new coroutine. It&#39;s like having a friend who starts a new game with you while you&#39;re already playing one. The new game runs alongside the current game, so you can have fun with both at the same time! You can use this builder to perform tasks simultaneously without waiting for one to finish before starting another.</li><li>async: This builder is like having a friend who helps you with a puzzle. They work on a piece of the puzzle while you work on another piece. Once both of you are done, you can put the puzzle pieces together. Similarly, the async builder helps us do tasks concurrently and retrieve results when they&#39;re ready. It&#39;s great for situations where one task doesn&#39;t depend on the other.</li><li>runBlocking: This builder is like having a special playtime where you pause everything else and focus on a specific task. It creates a special coroutine that blocks the execution of other coroutines until it&#39;s finished. It&#39;s useful when we want to do some tasks sequentially, one after the other.</li></ol><pre>fun main() {<br>    // Start a new coroutine using the launch builder<br>    GlobalScope.launch {<br>        println(&quot;Playing game A...&quot;)<br>        delay(1000)<br>        println(&quot;Game A completed!&quot;)<br>    }<br><br>    // Start a new coroutine using the async builder<br>    val gameB = GlobalScope.async {<br>        println(&quot;Playing game B...&quot;)<br>        delay(1500)<br>        println(&quot;Game B completed!&quot;)<br>        &quot;Game B result&quot;<br>    }<br><br>    // Do some other tasks while the coroutines are running<br>    println(&quot;Doing other tasks...&quot;)<br><br>    // Wait for the gameB coroutine to finish and get the result<br>    runBlocking {<br>        val result = gameB.await()<br>        println(&quot;Game B result: $result&quot;)<br>    }<br><br>    println(&quot;All tasks completed!&quot;)<br>}<br></pre><p>These coroutine builders make programming more fun and efficient, just like having different playtime options to choose from! They help us manage tasks and ensure that everything runs smoothly.</p><p>To summarize, coroutines are like juggling helpers for our computer programs. Suspending functions take breaks while waiting for things, and coroutine builders are like special assistants that help us create and manage coroutines.</p><p>Remember, it’s always good to have helpers in our lives, whether they’re coroutines in our programs or friends who support us. 😊 Have fun exploring the world of programming and coroutines! 🌟👩‍💻👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0bb2109833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock API response using Postman]]></title>
            <link>https://medium.com/@sourabhsharma_5073/testing-an-api-in-an-android-app-when-it-is-not-created-from-the-backend-can-be-difficult-because-2ae542171036?source=rss-db15d01f4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae542171036</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sourabh Sharma]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 14:32:52 GMT</pubDate>
            <atom:updated>2023-07-13T17:00:49.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxualKfho9JWv664mz4ILg.png" /></figure><p>Mock API on Postman for Android App</p><p>Testing an API in an Android app when it is not created from the backend can be difficult, because you cannot directly access the API to test it. However, there are a few things you can do to make it easier:</p><p>1 . Use a mock API. A mock API is a fake API that you can use to test your app’s code. You can create a mock API using a tool like Postman or Mockoon.<br>2 . Use a local development server. If you have access to the backend code, you can set up a local development server to run the API. This will allow you to test your app’s code against the real API.<br>3 . Use an HTTP client library. There are many HTTP client libraries available for Android. These libraries can make it easier to send requests to APIs and to handle the responses.</p><p>4 Charles Proxy for mocking API responses but It has limitations in terms of capabilities, scalability, collaboration, and integration, making dedicated mocking tools like Postman Mock Servers more suitable for comprehensive API response mocking during testing.</p><p>5 . There are services like <a href="https://www.mockable.io/">Mockable.io</a> which provide paid service .</p><p>We are going to use Postman to mock API response . Postman is a popular API development and testing tool used by developers, testers, and API consumers for various reasons. With Postman, you can create mock APIs to simulate API responses without implementing the actual backend logic. Mock servers help frontend developers or API consumers to start building or testing their applications even before the real API is available.</p><p>In Postman, you can mock API responses by creating a mock server and defining the expected responses for different API endpoints. Here’s how you can mock responses in Postman:</p><p>1. Create a Mock Server: In the Postman app, navigate to the “Mock Servers” tab and click on the “Create a Mock Server” button. Follow the prompts to configure the mock server settings such as name, description, region, environment, and advanced options.</p><p>2. Define Mock Responses: Once the mock server is created, you can define the expected responses for different API endpoints.</p><p>a. Select the mock server from the list and click on it to view its details.<br> b. Under the “Routes” section, click on the “Add Route” button to define a new endpoint.<br> c. Specify the request URL, method (GET, POST, etc.), and any other necessary request parameters.<br> d. Under the “Response” section, define the expected response for that endpoint.<br> e. Set the response status code, headers, and response body. You can provide static responses or use dynamic data using variables or response templates.</p><p>3. Customize Mock Responses (Optional): Postman provides additional options to customize the mock responses based on your testing requirements.</p><p>a. Use Dynamic Variables: You can define dynamic variables within the response body to generate dynamic data. These variables can be used to create unique IDs, random values, or timestamps.<br> b. Use Response Templates: Postman supports Handlebars templating syntax for response bodies. This allows you to customize the response dynamically based on input data or conditions using variables, loops, conditionals, etc.<br> c. Set Response Delays: You can introduce delays in the mock server responses to simulate real-world scenarios where API responses take some time to arrive. Set the desired delay time to test the behavior of your application in asynchronous operations.</p><p>4. Save and Use Mocked Responses: After defining the mock responses, save your changes. Postman will generate a unique URL for your mock server, which you can use in your application to mock the API responses.</p><p>5. Test and Verify: To test the mocked responses, send API requests to the generated mock server URL from your application or using Postman itself. You will receive the predefined responses based on the defined mock responses for each endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzSLN5aCQF_Sq0tdbDTD9g.png" /><figcaption>collection of the mocked api</figcaption></figure><p>By following these steps, you can effectively mock API responses in Postman. It allows you to simulate different scenarios and test your application’s behavior without relying on the actual backend API.</p><p>In conclusion, mock APIs are a valuable tool for testing and debugging Android apps. They allow you to simulate the behavior of a real API, without having to worry about the actual API being available. This can be a great way to save time and effort, and to ensure that your app is working correctly.</p><p>In this article, we have seen how to create and use mock APIs in Postman. We have also seen how to use mock APIs to test different scenarios, such as successful requests, failed requests, and unexpected errors.</p><p>I hope this article has been helpful. If you have any questions, please feel free to leave a comment below.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae542171036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boring Android Series : Kotlin Coroutine]]></title>
            <link>https://medium.com/@sourabhsharma_5073/boring-android-series-kotlin-coroutine-8259adc11cc8?source=rss-db15d01f4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8259adc11cc8</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Sourabh Sharma]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 12:01:56 GMT</pubDate>
            <atom:updated>2023-07-13T12:01:56.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZVBmfRCFP6xxKpGYI9cWg.png" /><figcaption>kotlin coroutine by shourabh</figcaption></figure><h3>Boring Android Series : Kotlin Coroutine</h3><p>In this blog, we will learn about Kotlin Coroutines in simple words. I know there are tons of blogs to learn Coroutine why am I writing another blog? <br>While I was learning Coroutine I realize that there is a need for a blog that teaches coroutine in simple words so that even a beginner can understand</p><p>Without Further Ado let’s get started, Imagine you are playing with your blocks. You want to build a house, but you also want to build a car. You could build the house first, and then the car. But that would take a long time.<br>Instead, you could use coroutines. Coroutines are like little blocks that can do their own thing. You can start building the house with one coroutine, and then start building the car with another coroutine. The coroutines will run at the same time, so you can build the house and the car at the same time.</p><p>here is an example of a Kotlin coroutine:</p><pre>fun main() {<br>  val houseCoroutine = launch {<br>    delay(1000)<br>    println(&quot;I built a house!&quot;)<br>  }<br><br>  val carCoroutine = launch {<br>    delay(2000)<br>    println(&quot;I built a car!&quot;)<br>  }<br><br>  houseCoroutine.join()<br>  carCoroutine.join()<br><br>  println(&quot;I&#39;m finished!&quot;)<br>}</pre><p>This code will print the following output:</p><pre>I built a house!<br>I built a car!<br>I&#39;m finished!</pre><p>The launch function starts a new coroutine. The delay function suspends the execution of the coroutine for a specified amount of time. The join function waits for the coroutine to finish executing.</p><p>In this example, the houseCoroutine and carCoroutine coroutines will run at the same time. The houseCoroutine will run for 1000 milliseconds, and then it will print the message &quot;I built a house!&quot;. The carCoroutine will run for 2000 milliseconds, and then it will print the message &quot;I built a car!&quot;.</p><p>Finally, the join functions will wait for the houseCoroutine and carCoroutine coroutines to finish executing. Once they are finished, the println function will print the message &quot;I&#39;m finished!&quot;.</p><p>You must we thinking join function is a suspending function, which means that it can be called from a coroutine. However, the main function is not a coroutine. So, how is it possible to call join from main?</p><p>The answer is that the main function is actually a special kind of coroutine called a blocking coroutine. Blocking coroutines are coroutines that can be called from non-coroutine code. When a blocking coroutine is called, it will suspend the execution of the non-coroutine code until the coroutine finishes executing.</p><p>In this example, the main function is a blocking coroutine. When the join function is called from main, it will suspend the execution of main until the coroutines that are being joined have finished executing. Once they are finished, the main function will resume executing and print the message &quot;I&#39;m finished!&quot;.</p><p>I hope this explanation helps!</p><p>When you are finished with one coroutine, it will stop running. But the other coroutine will keep running. So, you can keep building the car until you are finished.<br>Coroutines are a very powerful tool. They can help you to write code that is more efficient and more responsive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8259adc11cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>