<?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 Aman Garg on Medium]]></title>
        <description><![CDATA[Stories by Aman Garg on Medium]]></description>
        <link>https://medium.com/@amangarg2395?source=rss-37136cad8841------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MYLH5d4o3Wix3vb1SJDRhA.png</url>
            <title>Stories by Aman Garg on Medium</title>
            <link>https://medium.com/@amangarg2395?source=rss-37136cad8841------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:10:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amangarg2395/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[SOLID Principles in Android Development: A Comprehensive Guide with Kotlin]]></title>
            <link>https://medium.com/@amangarg2395/solid-principles-in-android-development-a-comprehensive-guide-with-kotlin-e1778f04beb8?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1778f04beb8</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 08:33:04 GMT</pubDate>
            <atom:updated>2025-10-03T08:33:04.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Solid Architecture" src="https://cdn-images-1.medium.com/max/640/1*8NQ4ViU8DKapDvoJr7CXaw.jpeg" /></figure><h3>Introduction</h3><p>Building robust Android applications requires more than just functional code. As Android developers, we often find ourselves dealing with complex requirements, changing business needs, and the necessity to maintain code over time. This is where SOLID principles become invaluable.</p><p>SOLID principles, introduced by Robert C. Martin, represent five fundamental design principles that guide developers toward creating maintainable, scalable, and robust software systems. In the context of Android development with Kotlin, these principles help us structure our code in a way that makes it easier to test, extend, and maintain.</p><p>In this comprehensive guide, we’ll explore each SOLID principle through practical Android examples written in Kotlin, complete with real-world analogies that make these concepts easier to understand and apply in your daily development work.</p><h3>What Are SOLID Principles?</h3><p>SOLID is an acronym representing five key principles:</p><ul><li><strong>S</strong> — Single Responsibility Principle (SRP)</li><li><strong>O</strong> — Open/Closed Principle (OCP)</li><li><strong>L</strong> — Liskov Substitution Principle (LSP)</li><li><strong>I</strong> — Interface Segregation Principle (ISP)</li><li><strong>D</strong> — Dependency Inversion Principle (DIP)</li></ul><p>These principles work together to create code that is more modular, easier to understand, and less prone to bugs when requirements change.</p><h3>1. Single Responsibility Principle (SRP)</h3><h3>Understanding the Principle</h3><p>The Single Responsibility Principle states that a class should have only one reason to change. In simpler terms, each class should focus on a single task or responsibility.</p><h3>Real-World Analogy</h3><p>Think of a restaurant kitchen. You wouldn’t expect the head chef to also serve tables, manage the cash register, and clean the floors. Each person has a specific role: the chef cooks, the waiter serves, the cashier handles payments, and the cleaner maintains the space. If the restaurant changes its payment system, only the cashier’s workflow needs to change, not the entire staff.</p><h3>Android Example: Violating SRP</h3><p>Here’s an example of a class that violates SRP:</p><pre>// BAD: Violating Single Responsibility Principle<br>class UserManager {<br>    fun registerUser(email: String, password: String): Boolean {<br>        // Validate user input<br>        if (email.isEmpty() || !email.contains(&quot;@&quot;)) {<br>            return false<br>        }<br>        <br>        // Save to database<br>        val database = Room.databaseBuilder(<br>            context,<br>            AppDatabase::class.java,<br>            &quot;user_database&quot;<br>        ).build()<br>        <br>        val user = User(email = email, password = password)<br>        database.userDao().insert(user)<br>        <br>        // Send welcome email<br>        val emailService = EmailService()<br>        emailService.sendWelcomeEmail(email)<br>        <br>        // Log the registration<br>        Log.d(&quot;UserManager&quot;, &quot;User registered: $email&quot;)<br>        <br>        return true<br>    }<br>}</pre><p>This class has multiple responsibilities: input validation, database operations, email sending, and logging. Any change in the email service, database structure, or validation rules would require modifying this single class.</p><h3>Android Example: Following SRP</h3><p>Here’s how we can refactor this to follow SRP:</p><pre>// GOOD: Following Single Responsibility Principle<br>// Handles only user validation<br>class UserValidator {<br>    fun validateRegistration(email: String, password: String): Boolean {<br>        return email.isNotEmpty() &amp;&amp; <br>               email.contains(&quot;@&quot;) &amp;&amp; <br>               password.length &gt;= 8<br>    }<br>}<br>// Handles only database operations<br>class UserRepository(private val userDao: UserDao) {<br>    suspend fun saveUser(user: User): Long {<br>        return userDao.insert(user)<br>    }<br>}<br>// Handles only email operations<br>class EmailService {<br>    fun sendWelcomeEmail(email: String) {<br>        // Email sending logic<br>    }<br>}<br>// Handles only logging<br>class UserLogger {<br>    fun logRegistration(email: String) {<br>        Log.d(&quot;UserRegistration&quot;, &quot;User registered: $email&quot;)<br>    }<br>}<br>// Coordinates the registration process<br>class UserRegistrationService(<br>    private val validator: UserValidator,<br>    private val repository: UserRepository,<br>    private val emailService: EmailService,<br>    private val logger: UserLogger<br>) {<br>    suspend fun registerUser(email: String, password: String): Boolean {<br>        if (!validator.validateRegistration(email, password)) {<br>            return false<br>        }<br>        <br>        val user = User(email = email, password = password)<br>        repository.saveUser(user)<br>        emailService.sendWelcomeEmail(email)<br>        logger.logRegistration(email)<br>        <br>        return true<br>    }<br>}</pre><p>Now each class has a single responsibility and can be tested, modified, and maintained independently.</p><h3>2. Open/Closed Principle (OCP)</h3><h3>Understanding the Principle</h3><p>The Open/Closed Principle states that software entities should be open for extension but closed for modification. This means you should be able to add new functionality without changing existing code.</p><h3>Real-World Analogy</h3><p>Consider a smartphone. When you want to add new functionality, you don’t modify the phone’s internal hardware. Instead, you install apps or connect accessories through standard interfaces like USB or Bluetooth. The phone is “closed” for modification (you can’t change its core functionality) but “open” for extension (you can add new features through apps and accessories).</p><h3>Android Example: Violating OCP</h3><p>Here’s an example that violates OCP:</p><pre>// BAD: Violating Open/Closed Principle<br>class PaymentProcessor {<br>    fun processPayment(amount: Double, paymentType: String): Boolean {<br>        when (paymentType) {<br>            &quot;CREDIT_CARD&quot; -&gt; {<br>                // Credit card processing logic<br>                Log.d(&quot;Payment&quot;, &quot;Processing credit card payment: $amount&quot;)<br>                return true<br>            }<br>            &quot;PAYPAL&quot; -&gt; {<br>                // PayPal processing logic<br>                Log.d(&quot;Payment&quot;, &quot;Processing PayPal payment: $amount&quot;)<br>                return true<br>            }<br>            &quot;GOOGLE_PAY&quot; -&gt; {<br>                // Google Pay processing logic<br>                Log.d(&quot;Payment&quot;, &quot;Processing Google Pay payment: $amount&quot;)<br>                return true<br>            }<br>            else -&gt; {<br>                return false<br>            }<br>        }<br>    }<br>}</pre><p>Every time we need to add a new payment method, we must modify the PaymentProcessor class, which violates OCP.</p><h3>Android Example: Following OCP</h3><p>Here’s how we can refactor this to follow OCP:</p><pre>// GOOD: Following Open/Closed Principle<br>// Abstract interface for payment processing<br>interface PaymentMethod {<br>    fun processPayment(amount: Double): Boolean<br>    fun getPaymentMethodName(): String<br>}<br>// Concrete implementations for different payment methods<br>class CreditCardPayment : PaymentMethod {<br>    override fun processPayment(amount: Double): Boolean {<br>        Log.d(&quot;Payment&quot;, &quot;Processing credit card payment: $amount&quot;)<br>        // Credit card processing logic<br>        return true<br>    }<br>    <br>    override fun getPaymentMethodName(): String = &quot;Credit Card&quot;<br>}<br>class PayPalPayment : PaymentMethod {<br>    override fun processPayment(amount: Double): Boolean {<br>        Log.d(&quot;Payment&quot;, &quot;Processing PayPal payment: $amount&quot;)<br>        // PayPal processing logic<br>        return true<br>    }<br>    <br>    override fun getPaymentMethodName(): String = &quot;PayPal&quot;<br>}<br>class GooglePayPayment : PaymentMethod {<br>    override fun processPayment(amount: Double): Boolean {<br>        Log.d(&quot;Payment&quot;, &quot;Processing Google Pay payment: $amount&quot;)<br>        // Google Pay processing logic<br>        return true<br>    }<br>    <br>    override fun getPaymentMethodName(): String = &quot;Google Pay&quot;<br>}<br>// Payment processor that works with any payment method<br>class PaymentProcessor {<br>    fun processPayment(amount: Double, paymentMethod: PaymentMethod): Boolean {<br>        return paymentMethod.processPayment(amount)<br>    }<br>}<br>// Usage example<br>class CheckoutActivity : AppCompatActivity() {<br>    private val paymentProcessor = PaymentProcessor()<br>    <br>    private fun processPayment(amount: Double, selectedMethod: String) {<br>        val paymentMethod = when (selectedMethod) {<br>            &quot;credit_card&quot; -&gt; CreditCardPayment()<br>            &quot;paypal&quot; -&gt; PayPalPayment()<br>            &quot;google_pay&quot; -&gt; GooglePayPayment()<br>            else -&gt; throw IllegalArgumentException(&quot;Unsupported payment method&quot;)<br>        }<br>        <br>        paymentProcessor.processPayment(amount, paymentMethod)<br>    }<br>}</pre><p>Now we can add new payment methods by simply creating new implementations of PaymentMethod without modifying existing code.</p><h3>3. Liskov Substitution Principle (LSP)</h3><h3>Understanding the Principle</h3><p>The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. In other words, if class B is a subtype of class A, then objects of type A should be replaceable with objects of type B without altering any of the desirable properties of the program.</p><h3>Real-World Analogy</h3><p>Think about different types of vehicles in a car rental service. Whether you rent a sedan, SUV, or hatchback, you should be able to drive any of them using the same basic operations: start the engine, accelerate, brake, and steer. The rental service can substitute one type of car for another, and you should still be able to drive it without learning completely new controls.</p><h3>Android Example: Violating LSP</h3><p>Here’s an example that violates LSP:</p><pre>// BAD: Violating Liskov Substitution Principle<br>abstract class Bird {<br>    abstract fun fly(): String<br>    abstract fun makeSound(): String<br>}<br>class Sparrow : Bird() {<br>    override fun fly(): String {<br>        return &quot;Sparrow flying high in the sky&quot;<br>    }<br>    <br>    override fun makeSound(): String {<br>        return &quot;Chirp chirp&quot;<br>    }<br>}<br>class Penguin : Bird() {<br>    override fun fly(): String {<br>        // Penguins can&#39;t fly! This violates LSP<br>        throw UnsupportedOperationException(&quot;Penguins cannot fly&quot;)<br>    }<br>    <br>    override fun makeSound(): String {<br>        return &quot;Squawk&quot;<br>    }<br>}<br>// Usage that breaks when using Penguin<br>class BirdWatcher {<br>    fun observeBirdFlight(bird: Bird): String {<br>        return bird.fly() // This will crash if bird is a Penguin<br>    }<br>}</pre><h3>Android Example: Following LSP</h3><p>Here’s how we can refactor this to follow LSP:</p><pre>// GOOD: Following Liskov Substitution Principle<br>// Base interface for all birds<br>interface Bird {<br>    fun makeSound(): String<br>    fun getSpecies(): String<br>}<br>// Separate interface for birds that can fly<br>interface FlyingBird : Bird {<br>    fun fly(): String<br>}<br>// Separate interface for birds that can swim<br>interface SwimmingBird : Bird {<br>    fun swim(): String<br>}<br>// Flying birds implement FlyingBird<br>class Sparrow : FlyingBird {<br>    override fun makeSound(): String = &quot;Chirp chirp&quot;<br>    <br>    override fun getSpecies(): String = &quot;Sparrow&quot;<br>    <br>    override fun fly(): String = &quot;Sparrow flying high in the sky&quot;<br>}<br>class Eagle : FlyingBird {<br>    override fun makeSound(): String = &quot;Screech&quot;<br>    <br>    override fun getSpecies(): String = &quot;Eagle&quot;<br>    <br>    override fun fly(): String = &quot;Eagle soaring majestically&quot;<br>}<br>// Swimming birds implement SwimmingBird<br>class Penguin : SwimmingBird {<br>    override fun makeSound(): String = &quot;Squawk&quot;<br>    <br>    override fun getSpecies(): String = &quot;Penguin&quot;<br>    <br>    override fun swim(): String = &quot;Penguin swimming gracefully underwater&quot;<br>}<br>// Usage classes that respect the substitution principle<br>class BirdWatcher {<br>    fun observeAllBirds(birds: List&lt;Bird&gt;) {<br>        birds.forEach { bird -&gt;<br>            println(&quot;${bird.getSpecies()}: ${bird.makeSound()}&quot;)<br>        }<br>    }<br>    <br>    fun observeFlyingBirds(flyingBirds: List&lt;FlyingBird&gt;) {<br>        flyingBirds.forEach { bird -&gt;<br>            println(&quot;${bird.getSpecies()}: ${bird.fly()}&quot;)<br>        }<br>    }<br>    <br>    fun observeSwimmingBirds(swimmingBirds: List&lt;SwimmingBird&gt;) {<br>        swimmingBirds.forEach { bird -&gt;<br>            println(&quot;${bird.getSpecies()}: ${bird.swim()}&quot;)<br>        }<br>    }<br>}</pre><p>Now we can substitute any Bird implementation without breaking the application, and we have specific interfaces for different behaviors.</p><h3>4. Interface Segregation Principle (ISP)</h3><h3>Understanding the Principle</h3><p>The Interface Segregation Principle states that clients should not be forced to depend on methods they don’t use. Instead of creating large, monolithic interfaces, we should create smaller, more specific interfaces.</p><h3>Real-World Analogy</h3><p>Think of a restaurant menu. A vegetarian customer shouldn’t have to see or deal with meat dishes when ordering. Similarly, a customer who only wants drinks shouldn’t have to navigate through food items. A good restaurant might have separate menus: a vegetarian menu, a non-vegetarian menu, a drinks menu, and a dessert menu. This way, each customer only interacts with what’s relevant to them.</p><h3>Android Example: Violating ISP</h3><p>Here’s an example that violates ISP:</p><pre>// BAD: Violating Interface Segregation Principle<br>interface MediaPlayer {<br>    fun playAudio(audioFile: String)<br>    fun pauseAudio()<br>    fun stopAudio()<br>    fun playVideo(videoFile: String)<br>    fun pauseVideo()<br>    fun stopVideo()<br>    fun adjustBrightness(level: Int)<br>    fun adjustVolume(level: Int)<br>    fun enableSubtitles(enabled: Boolean)<br>    fun setPlaybackSpeed(speed: Float)<br>}<br><br>// Audio-only player forced to implement video methods<br>class AudioOnlyPlayer : MediaPlayer {<br>    override fun playAudio(audioFile: String) {<br>        println(&quot;Playing audio: $audioFile&quot;)<br>    }<br>    <br>    override fun pauseAudio() {<br>        println(&quot;Audio paused&quot;)<br>    }<br>    <br>    override fun stopAudio() {<br>        println(&quot;Audio stopped&quot;)<br>    }<br>    <br>    // Forced to implement video methods even though not needed<br>    override fun playVideo(videoFile: String) {<br>        throw UnsupportedOperationException(&quot;Audio player doesn&#39;t support video&quot;)<br>    }<br>    <br>    override fun pauseVideo() {<br>        throw UnsupportedOperationException(&quot;Audio player doesn&#39;t support video&quot;)<br>    }<br>    <br>    override fun stopVideo() {<br>        throw UnsupportedOperationException(&quot;Audio player doesn&#39;t support video&quot;)<br>    }<br>    <br>    override fun adjustBrightness(level: Int) {<br>        throw UnsupportedOperationException(&quot;Audio player doesn&#39;t have brightness control&quot;)<br>    }<br>    <br>    override fun adjustVolume(level: Int) {<br>        println(&quot;Volume adjusted to: $level&quot;)<br>    }<br>    <br>    override fun enableSubtitles(enabled: Boolean) {<br>        throw UnsupportedOperationException(&quot;Audio player doesn&#39;t support subtitles&quot;)<br>    }<br>    <br>    override fun setPlaybackSpeed(speed: Float) {<br>        println(&quot;Playback speed set to: ${speed}x&quot;)<br>    }<br>}</pre><h3>Android Example: Following ISP</h3><p>Here’s how we can refactor this to follow ISP:</p><pre>// GOOD: Following Interface Segregation Principle<br>// Core media interface<br>interface MediaPlayback {<br>    fun play(mediaFile: String)<br>    fun pause()<br>    fun stop()<br>}<br>// Audio-specific interface<br>interface AudioPlayback : MediaPlayback {<br>    fun adjustVolume(level: Int)<br>    fun setPlaybackSpeed(speed: Float)<br>}<br>// Video-specific interface<br>interface VideoPlayback : MediaPlayback {<br>    fun adjustBrightness(level: Int)<br>    fun enableSubtitles(enabled: Boolean)<br>    fun setPlaybackSpeed(speed: Float)<br>}<br>// Volume control interface<br>interface VolumeControl {<br>    fun adjustVolume(level: Int)<br>    fun mute()<br>    fun unmute()<br>}<br>// Audio player implements only what it needs<br>class AudioPlayer : AudioPlayback, VolumeControl {<br>    override fun play(mediaFile: String) {<br>        println(&quot;Playing audio: $mediaFile&quot;)<br>    }<br>    <br>    override fun pause() {<br>        println(&quot;Audio paused&quot;)<br>    }<br>    <br>    override fun stop() {<br>        println(&quot;Audio stopped&quot;)<br>    }<br>    <br>    override fun adjustVolume(level: Int) {<br>        println(&quot;Volume adjusted to: $level&quot;)<br>    }<br>    <br>    override fun setPlaybackSpeed(speed: Float) {<br>        println(&quot;Playback speed set to: ${speed}x&quot;)<br>    }<br>    <br>    override fun mute() {<br>        println(&quot;Audio muted&quot;)<br>    }<br>    <br>    override fun unmute() {<br>        println(&quot;Audio unmuted&quot;)<br>    }<br>}<br>// Video player implements video-specific functionality<br>class VideoPlayer : VideoPlayback, VolumeControl {<br>    override fun play(mediaFile: String) {<br>        println(&quot;Playing video: $mediaFile&quot;)<br>    }<br>    <br>    override fun pause() {<br>        println(&quot;Video paused&quot;)<br>    }<br>    <br>    override fun stop() {<br>        println(&quot;Video stopped&quot;)<br>    }<br>    <br>    override fun adjustBrightness(level: Int) {<br>        println(&quot;Brightness adjusted to: $level&quot;)<br>    }<br>    <br>    override fun enableSubtitles(enabled: Boolean) {<br>        println(&quot;Subtitles ${if (enabled) &quot;enabled&quot; else &quot;disabled&quot;}&quot;)<br>    }<br>    <br>    override fun setPlaybackSpeed(speed: Float) {<br>        println(&quot;Video playback speed set to: ${speed}x&quot;)<br>    }<br>    <br>    override fun adjustVolume(level: Int) {<br>        println(&quot;Volume adjusted to: $level&quot;)<br>    }<br>    <br>    override fun mute() {<br>        println(&quot;Video muted&quot;)<br>    }<br>    <br>    override fun unmute() {<br>        println(&quot;Video unmuted&quot;)<br>    }<br>}<br>// Usage in Android activity<br>class MediaActivity : AppCompatActivity() {<br>    private lateinit var audioPlayer: AudioPlayer<br>    private lateinit var videoPlayer: VideoPlayer<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <br>        audioPlayer = AudioPlayer()<br>        videoPlayer = VideoPlayer()<br>        <br>        // Can use audio player for audio-specific operations<br>        handleAudioPlayback(audioPlayer)<br>        <br>        // Can use video player for video-specific operations<br>        handleVideoPlayback(videoPlayer)<br>        <br>        // Can use both for volume control<br>        handleVolumeControl(audioPlayer)<br>        handleVolumeControl(videoPlayer)<br>    }<br>    <br>    private fun handleAudioPlayback(player: AudioPlayback) {<br>        player.play(&quot;audio.mp3&quot;)<br>        player.setPlaybackSpeed(1.5f)<br>    }<br>    <br>    private fun handleVideoPlayback(player: VideoPlayback) {<br>        player.play(&quot;video.mp4&quot;)<br>        player.enableSubtitles(true)<br>    }<br>    <br>    private fun handleVolumeControl(volumeControl: VolumeControl) {<br>        volumeControl.adjustVolume(80)<br>    }<br>}</pre><p>Now each interface is focused on a specific responsibility, and classes only implement the methods they actually need.</p><h3>5. Dependency Inversion Principle (DIP)</h3><h3>Understanding the Principle</h3><p>The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details; details should depend on abstractions.</p><h3>Real-World Analogy</h3><p>Think of electrical appliances in your home. Your television doesn’t depend on a specific power plant or electrical grid configuration. Instead, it depends on the abstraction of a standardized electrical outlet. Whether your electricity comes from solar power, nuclear energy, or coal, your TV works the same way because it depends on the standard electrical interface, not the specific source of power.</p><h3>Android Example: Violating DIP</h3><p>Here’s an example that violates DIP:</p><pre>// BAD: Violating Dependency Inversion Principle<br>// Low-level module - concrete implementation<br>class LocalUserRepository {<br>    fun saveUser(user: User): Boolean {<br>        // Save user to local database<br>        println(&quot;Saving user to local database: ${user.name}&quot;)<br>        return true<br>    }<br>    <br>    fun getUser(userId: Int): User? {<br>        // Get user from local database<br>        return User(userId, &quot;John Doe&quot;, &quot;john@example.com&quot;)<br>    }<br>}<br>// High-level module depending on low-level module<br>class UserService {<br>    // Direct dependency on concrete class<br>    private val userRepository = LocalUserRepository()<br>    <br>    fun registerUser(name: String, email: String): Boolean {<br>        val user = User(0, name, email)<br>        return userRepository.saveUser(user)<br>    }<br>    <br>    fun getUserProfile(userId: Int): User? {<br>        return userRepository.getUser(userId)<br>    }<br>}<br>// Data class<br>data class User(val id: Int, val name: String, val email: String)</pre><p>In this example, UserService (high-level) directly depends on LocalUserRepository (low-level), making it difficult to test and inflexible to changes.</p><h3>Android Example: Following DIP</h3><p>Here’s how we can refactor this to follow DIP:</p><pre>// GOOD: Following Dependency Inversion Principle<br>// Data class<br>data class User(val id: Int, val name: String, val email: String)<br>// Abstraction - high-level interface<br>interface UserRepository {<br>    suspend fun saveUser(user: User): Boolean<br>    suspend fun getUser(userId: Int): User?<br>    suspend fun getAllUsers(): List&lt;User&gt;<br>}<br>// Low-level modules implementing the abstraction<br>class LocalUserRepository(private val userDao: UserDao) : UserRepository {<br>    override suspend fun saveUser(user: User): Boolean {<br>        return try {<br>            userDao.insert(user)<br>            true<br>        } catch (e: Exception) {<br>            false<br>        }<br>    }<br>    <br>    override suspend fun getUser(userId: Int): User? {<br>        return userDao.getUserById(userId)<br>    }<br>    <br>    override suspend fun getAllUsers(): List&lt;User&gt; {<br>        return userDao.getAllUsers()<br>    }<br>}<br>class RemoteUserRepository(private val apiService: UserApiService) : UserRepository {<br>    override suspend fun saveUser(user: User): Boolean {<br>        return try {<br>            val response = apiService.createUser(user)<br>            response.isSuccessful<br>        } catch (e: Exception) {<br>            false<br>        }<br>    }<br>    <br>    override suspend fun getUser(userId: Int): User? {<br>        return try {<br>            val response = apiService.getUser(userId)<br>            if (response.isSuccessful) response.body() else null<br>        } catch (e: Exception) {<br>            null<br>        }<br>    }<br>    <br>    override suspend fun getAllUsers(): List&lt;User&gt; {<br>        return try {<br>            val response = apiService.getAllUsers()<br>            response.body() ?: emptyList()<br>        } catch (e: Exception) {<br>            emptyList()<br>        }<br>    }<br>}<br>// High-level module depending on abstraction<br>class UserService(private val userRepository: UserRepository) {<br>    suspend fun registerUser(name: String, email: String): Boolean {<br>        val user = User(0, name, email)<br>        return userRepository.saveUser(user)<br>    }<br>    <br>    suspend fun getUserProfile(userId: Int): User? {<br>        return userRepository.getUser(userId)<br>    }<br>    <br>    suspend fun getAllUserProfiles(): List&lt;User&gt; {<br>        return userRepository.getAllUsers()<br>    }<br>}<br>// Dependency injection setup using Hilt<br>@Module<br>@InstallIn(SingletonComponent::class)<br>abstract class RepositoryModule {<br>    <br>    @Binds<br>    abstract fun bindUserRepository(<br>        localUserRepository: LocalUserRepository<br>    ): UserRepository<br>}<br>@Singleton<br>class LocalUserRepository @Inject constructor(<br>    private val userDao: UserDao<br>) : UserRepository {<br>    // Implementation as shown above<br>}<br>// Usage in Android ViewModel<br>@HiltViewModel<br>class UserViewModel @Inject constructor(<br>    private val userService: UserService<br>) : ViewModel() {<br>    <br>    private val _users = MutableLiveData&lt;List&lt;User&gt;&gt;()<br>    val users: LiveData&lt;List&lt;User&gt;&gt; = _users<br>    <br>    private val _loading = MutableLiveData&lt;Boolean&gt;()<br>    val loading: LiveData&lt;Boolean&gt; = _loading<br>    <br>    fun loadUsers() {<br>        viewModelScope.launch {<br>            _loading.value = true<br>            try {<br>                val userList = userService.getAllUserProfiles()<br>                _users.value = userList<br>            } catch (e: Exception) {<br>                // Handle error<br>            } finally {<br>                _loading.value = false<br>            }<br>        }<br>    }<br>    <br>    fun registerUser(name: String, email: String) {<br>        viewModelScope.launch {<br>            _loading.value = true<br>            try {<br>                val success = userService.registerUser(name, email)<br>                if (success) {<br>                    loadUsers() // Refresh the list<br>                }<br>            } catch (e: Exception) {<br>                // Handle error<br>            } finally {<br>                _loading.value = false<br>            }<br>        }<br>    }<br>}<br>// Testing becomes much easier<br>class UserServiceTest {<br>    <br>    @Mock<br>    private lateinit var mockUserRepository: UserRepository<br>    <br>    private lateinit var userService: UserService<br>    <br>    @Before<br>    fun setup() {<br>        MockitoAnnotations.openMocks(this)<br>        userService = UserService(mockUserRepository)<br>    }<br>    <br>    @Test<br>    fun `registerUser should return true when repository saves successfully`() = runTest {<br>        // Given<br>        val testUser = User(0, &quot;Test User&quot;, &quot;test@example.com&quot;)<br>        `when`(mockUserRepository.saveUser(any())).thenReturn(true)<br>        <br>        // When<br>        val result = userService.registerUser(&quot;Test User&quot;, &quot;test@example.com&quot;)<br>        <br>        // Then<br>        assertTrue(result)<br>        verify(mockUserRepository).saveUser(any())<br>    }<br>}</pre><p>Now the UserService depends on the UserRepository abstraction, not concrete implementations. This makes the code more flexible, testable, and maintainable.</p><h3>Benefits of Applying SOLID Principles in Android Development</h3><h3>1. Enhanced Testability</h3><p>When your code follows SOLID principles, it becomes much easier to write unit tests. Each class has a single responsibility, dependencies are injected, and you can easily mock interfaces for testing.</p><pre>// Easy to test because of dependency injection<br>class UserViewModelTest {<br>    @Mock private lateinit var userService: UserService<br>    private lateinit var viewModel: UserViewModel<br>    <br>    @Before<br>    fun setup() {<br>        viewModel = UserViewModel(userService)<br>    }<br>    <br>    @Test<br>    fun `loadUsers should update users LiveData`() {<br>        // Test implementation<br>    }<br>}</pre><h3>2. Better Maintainability</h3><p>Changes to one part of your application are less likely to break other parts when you follow SOLID principles. This is especially important in Android development, where requirements change frequently.</p><h3>3. Improved Scalability</h3><p>As your Android app grows, SOLID principles help you add new features without modifying existing code, reducing the risk of introducing bugs.</p><h3>4. Code Reusability</h3><p>Following these principles encourages the creation of reusable components that can be used across different parts of your application or even in different projects.</p><h3>Common Android Patterns That Embrace SOLID Principles</h3><h4>1. Repository Pattern</h4><p>The Repository pattern naturally follows the Dependency Inversion Principle by abstracting data sources.</p><h4>2. MVVM Architecture</h4><p>Model-View-ViewModel architecture promotes separation of concerns, aligning with the Single Responsibility Principle.</p><h4>3. Dependency Injection with Hilt</h4><p>Hilt makes it easier to follow the Dependency Inversion Principle by managing dependencies for you.</p><h4>4. Use Cases/Interactors</h4><p>Use cases encapsulate business logic, following the Single Responsibility Principle.</p><p>SOLID principles are not just theoretical concepts but practical guidelines that can significantly improve the quality of your Android applications. By following these principles, you create code that is more maintainable, testable, and adaptable to changing requirements.</p><p>As you continue your Android development journey, keep these principles in mind, and you’ll find that your code becomes not only more professional but also more enjoyable to work with and maintain!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1778f04beb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Bundles in Android]]></title>
            <link>https://medium.com/devjoint/dependency-bundles-in-android-25e67ba6e98e?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e67ba6e98e</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 06:36:13 GMT</pubDate>
            <atom:updated>2025-02-10T06:36:13.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25FXy5tCGUQuS-vJ5NhJeg.png" /></figure><p>Dependency bundles are a powerful feature of Gradle’s version catalog, defined in the libs.versions.toml file. They allow you to group multiple related dependencies under a single identifier, simplifying your build files and making dependency management cleaner.</p><h3>Why Use Dependency Bundles?</h3><ol><li><strong>Cleaner Build Files:</strong> Instead of adding each dependency manually, you can use a single line for related dependencies.</li><li><strong>Better Maintainability:</strong> Group dependencies logically, such as UI libraries, testing tools, or networking components.</li><li><strong>Consistency:</strong> Ensure consistent dependency usage across modules by defining bundles centrally.</li></ol><h3>How to Define Dependency Bundles</h3><p>In the libs.versions.toml file:</p><pre>[versions]<br>retrofit = &quot;2.9.0&quot;<br>okhttp = &quot;4.10.0&quot;<br><br>[libraries]<br>retrofit = { module = &quot;com.squareup.retrofit2:retrofit&quot;, version.ref = &quot;retrofit&quot; }<br>okhttp = { module = &quot;com.squareup.okhttp3:okhttp&quot;, version.ref = &quot;okhttp&quot; }<br><br>[bundles]<br>networking = [&quot;retrofit&quot;, &quot;okhttp&quot;]</pre><h3>How to Use Bundles in Build Files</h3><p>In your build.gradle.kts file:</p><pre>dependencies {<br>    implementation(libs.bundles.networking)<br>}</pre><h3>Best Practices</h3><ul><li>Group related dependencies, such as UI components, testing libraries, or data management tools.</li><li>Keep the libs.versions.toml file organized with clear comments.</li><li>Always reference library versions through the versions block to maintain consistency.</li></ul><p>Dependency bundles help Android developers maintain cleaner, more maintainable projects by simplifying dependency declarations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e67ba6e98e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/dependency-bundles-in-android-25e67ba6e98e">Dependency Bundles in Android</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns in RecyclerView]]></title>
            <link>https://medium.com/devjoint/design-patterns-in-recyclerview-2dad061fe07f?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dad061fe07f</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 10:10:50 GMT</pubDate>
            <atom:updated>2025-01-26T10:10:50.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6xmJ8NeTx40fhZLSWhi_A.jpeg" /><figcaption>Design Patterns</figcaption></figure><p><strong>RecyclerView</strong> is a powerful component in Android, and its architecture is built on various <strong>design patterns</strong> that make it flexible, efficient, and scalable. Here’s a quick look at the key design patterns it utilizes:</p><h3>1. Adapter Pattern</h3><ul><li><strong>Where</strong>: RecyclerView.Adapter</li><li><strong>What It Does</strong>: Acts as a bridge between the data source and RecyclerView, binding data to the UI.</li><li><strong>Why It Matters</strong>: Keeps RecyclerView decoupled from the actual data source, promoting flexibility.</li></ul><h3>2. ViewHolder Pattern</h3><ul><li><strong>Where</strong>: RecyclerView.ViewHolder</li><li><strong>What It Does</strong>: Holds references to views, avoiding repeated findViewById() calls.</li><li><strong>Why It Matters</strong>: Enhances performance by caching views for reuse.</li></ul><h3>3. Observer Pattern</h3><ul><li><strong>Where</strong>: AdapterDataObserver</li><li><strong>What It Does</strong>: Keeps RecyclerView updated when the dataset changes (e.g., notifyDataSetChanged() is called).</li><li><strong>Why It Matters</strong>: Ensures a reactive UI that responds to data changes dynamically.</li></ul><h3>4. Strategy Pattern</h3><ul><li><strong>Where</strong>: LayoutManager</li><li><strong>What It Does</strong>: Defines how items are laid out (e.g., LinearLayoutManager, GridLayoutManager).</li><li><strong>Why It Matters</strong>: Allows flexible layout strategies without modifying the core RecyclerView.</li></ul><h3>5. Decorator Pattern</h3><ul><li><strong>Where</strong>: ItemDecoration</li><li><strong>What It Does</strong>: Adds visual decorations (e.g., dividers, spacing) without altering item views.</li><li><strong>Why It Matters</strong>: Enhances visuals while keeping item views clean.</li></ul><h3>6. Factory Pattern</h3><ul><li><strong>Where</strong>: RecyclerView.Adapter.onCreateViewHolder()</li><li><strong>What It Does</strong>: Creates ViewHolder objects when needed.</li><li><strong>Why It Matters</strong>: Supports dynamic creation of ViewHolders based on item types.</li></ul><h3>Why RecyclerView Excels</h3><p>By combining these patterns, RecyclerView achieves:</p><ul><li>High performance.</li><li>Scalability for large datasets.</li><li>Easy customization and flexibility.</li></ul><p><strong>Understanding these patterns is key to mastering RecyclerView in Android!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dad061fe07f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/design-patterns-in-recyclerview-2dad061fe07f">Design Patterns in RecyclerView</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Simplified: Understanding Stateful and Stateless Components]]></title>
            <link>https://medium.com/devjoint/jetpack-compose-simplified-understanding-stateful-and-stateless-components-ac71f7cae79b?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac71f7cae79b</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 10:58:09 GMT</pubDate>
            <atom:updated>2024-07-28T10:58:09.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aug8jjP4ofu59e3u" /><figcaption>Photo by <a href="https://unsplash.com/@pdcck?utm_source=medium&amp;utm_medium=referral">Platforma za Društveni centar Čakovec</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Understanding the difference between stateful and stateless components in Jetpack Compose can seem tricky, but let’s break it down into simple terms. We’ll explore what these concepts mean, provide examples, compare them, and discuss their pros and cons. By the end, you’ll have a clear understanding of how to use both in your app development.</p><h3>What is Jetpack Compose?</h3><p>Jetpack Compose is a modern toolkit for building native Android UIs. It simplifies and accelerates UI development with less code, powerful tools, and intuitive Kotlin APIs. One of the core concepts in Jetpack Compose is the idea of “state.” Let’s dive into what that means.</p><h3>Stateless Components</h3><h4>What Are They?</h4><p>A stateless component is like a book. A book displays the same content every time you open it unless you manually change something inside it. In the context of Jetpack Compose, a stateless component doesn’t remember any changes. It just displays what it’s given every time it’s called.</p><h4>Example:</h4><p>Let’s look at a simple greeting message component.</p><pre>@Composable<br>fun Greeting(name: String) {<br>    Text(text = &quot;Hello, $name!&quot;)<br>}</pre><p>In this example, the Greeting function is stateless. It takes a name and shows &quot;Hello, [name]!&quot; each time. If you pass &quot;Alice&quot; as the name, it will always display &quot;Hello, Alice!&quot; until you provide a different name.</p><h4>Pros and Cons:</h4><p><strong>Advantages:</strong></p><ul><li><strong>Simplicity</strong>: Easy to read, understand, and test.</li><li><strong>Reusability</strong>: Can be used in many different places with different data.</li><li><strong>Performance</strong>: Generally faster because it doesn’t manage state.</li></ul><p><strong>Disadvantages:</strong></p><ul><li><strong>Limited Functionality</strong>: Can’t handle dynamic changes or user interactions well.</li></ul><h3>Stateful Components</h3><h4>What Are They?</h4><p>A stateful component is like a TV remote. It remembers which button you pressed last and changes the TV display based on that. In Jetpack Compose, a stateful component keeps track of what’s happening and responds to changes. It manages its own state internally.</p><h4>Example:</h4><p>Consider a button that counts how many times you click it.</p><pre>@Composable<br>fun ClickCounter() {<br>    var count by remember { mutableStateOf(0) }<br><br>    Button(onClick = { count++ }) {<br>        Text(text = &quot;Clicked $count times&quot;)<br>    }<br>}</pre><p>In this example, the ClickCounter function is stateful. It remembers how many times you&#39;ve clicked the button and updates the displayed number each time you click it.</p><h4>Pros and Cons:</h4><p><strong>Advantages:</strong></p><ul><li><strong>Dynamic Functionality</strong>: Can handle user interactions and changes over time.</li><li><strong>Rich Features</strong>: Supports complex, interactive UIs.</li></ul><p><strong>Disadvantages:</strong></p><ul><li><strong>Complexity</strong>: Harder to understand, test, and maintain.</li><li><strong>Performance</strong>: Can be slower due to state management.</li></ul><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2aQjC_PJc31Bi4csQJjow.png" /></figure><h3>When to Use Each</h3><p><strong>Stateless Components</strong> are ideal for:</p><ul><li>Displaying static data that doesn’t change.</li><li>Simple UI elements that don’t interact with the user.</li><li>Components that need to be highly reusable across different parts of your app.</li></ul><p><strong>Stateful Components</strong> are ideal for:</p><ul><li>Interactive elements that respond to user input.</li><li>Dynamic data that changes over time.</li><li>Complex UIs that need to manage their own state.</li></ul><h3>Conclusion</h3><p>Understanding when to use stateful versus stateless components is crucial in building efficient and maintainable UIs with Jetpack Compose. Stateless components are simple, reusable, and performant, making them perfect for static displays. On the other hand, stateful components are essential for handling dynamic, interactive content, despite being more complex and potentially slower.</p><p>By mastering both, you can create powerful and flexible Android apps that offer a great user experience. Happy composing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac71f7cae79b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/jetpack-compose-simplified-understanding-stateful-and-stateless-components-ac71f7cae79b">Jetpack Compose Simplified: Understanding Stateful and Stateless Components</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Simplified: Mastering Kotlin Scopes with Effect Handlers and Side Effects]]></title>
            <link>https://medium.com/devjoint/jetpack-compose-simplified-mastering-kotlin-scopes-with-effect-handlers-and-side-effects-9b65ea07b3ce?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b65ea07b3ce</guid>
            <category><![CDATA[side-effects]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 10:03:55 GMT</pubDate>
            <atom:updated>2024-07-28T10:03:55.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pDnn5bErIX0Csr3j" /><figcaption>Photo by <a href="https://unsplash.com/@devintavery?utm_source=medium&amp;utm_medium=referral">Devin Avery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. When working with Jetpack Compose, you’ll come across various scopes and effects. In this blog, we’ll explore them in simple terms with easy examples, divided into Suspend and Non-Suspend Effect Handlers, and Side Effect States.</p><h3>Effect Handlers</h3><h3>Suspend Effect Handlers</h3><p>These handlers are used when you need to perform tasks that involve suspending functions, such as network requests or long-running operations.</p><h4>1. LaunchedEffect</h4><p>LaunchedEffect is a composable function that runs a coroutine when a key changes. It is often used to start a coroutine that performs some work when a specific state changes.</p><h4>Example</h4><pre>@Composable<br>fun MyScreen(userId: String) {<br>    var userData by remember { mutableStateOf&lt;User?&gt;(null) }<br><br>    LaunchedEffect(userId) {<br>        // Simulate a network call<br>        userData = fetchUserData(userId)<br>    }<br><br>    // UI based on userData<br>    userData?.let {<br>        Text(text = &quot;User Name: ${it.name}&quot;)<br>    } ?: run {<br>        CircularProgressIndicator()<br>    }<br>}</pre><p>In this example, LaunchedEffect will fetch user data whenever the userId changes.</p><h4>2. rememberCoroutineScope</h4><p>rememberCoroutineScope provides a coroutine scope that is bound to the lifecycle of the 2. SideEffect.</p><h4>Example</h4><pre>@Composable<br>fun MyButton() {<br>    val scope = rememberCoroutineScope()<br><br>    Button(onClick = {<br>        scope.launch {<br>            // Perform some long-running task<br>            performTask()<br>        }<br>    }) {<br>        Text(&quot;Start Task&quot;)<br>    }<br>}</pre><p>Here, rememberCoroutineScope gives us a coroutine scope to launch a task when the button is clicked.</p><h3>Non-Suspend Effect Handlers</h3><p>These handlers are used for tasks that do not involve suspending functions but still require lifecycle-aware handling.</p><h4>1. DisposableEffect</h4><p>DisposableEffect is used for side effects that need to be cleaned up when the key changes or the composable leaves the composition.</p><h4>Example</h4><pre>@Composable<br>fun MySensorComponent() {<br>    DisposableEffect(Unit) {<br>        val sensor = SensorManager()<br>        sensor.startListening()<br>        <br>        onDispose {<br>            sensor.stopListening()<br>        }<br>    }<br><br>    // UI elements<br>    Text(&quot;Listening to sensor data...&quot;)<br>}</pre><p>In this example, the sensor starts listening when the composable enters the composition and stops when it leaves.</p><h4>2. SideEffect</h4><p>SideEffect is used to perform side effects that need to happen after a successful composition.</p><h4>Example</h4><pre>@Composable<br>fun MySideEffectComponent(data: String) {<br>SideEffect {<br>        Log.d(&quot;MySideEffectComponent&quot;, &quot;Data: $data&quot;)<br>    }<br><br>    // UI elements<br>    Text(text = data)<br>}</pre><p>Here, SideEffect logs data every time the composable recomposes with new data.</p><h3>Side Effect States</h3><h4>1. rememberUpdatedState</h4><p>rememberUpdatedState helps to safely capture a value in a composable that might change.</p><h4>Example</h4><pre>@Composable<br>fun TimerComponent(onTimeout: () -&gt; Unit) {<br>    val currentOnTimeout by rememberUpdatedState(onTimeout)<br><br>    LaunchedEffect(Unit) {<br>        delay(3000)<br>        currentOnTimeout()<br>    }<br><br>    Text(&quot;Timer started...&quot;)<br>}</pre><p>In this example, rememberUpdatedState ensures onTimeout is always up-to-date.</p><h4>2. derivedStateOf</h4><p>derivedStateOf is used to create a state that depends on other states.</p><h4>Example</h4><pre>@Composable<br>fun MyDerivedStateComponent(items: List&lt;String&gt;) {<br>    val itemCount by remember { derivedStateOf { items.size } }<br><br>    Text(&quot;Item count: $itemCount&quot;)<br>}</pre><p>Here, itemCount is derived from items and will update whenever items changes.</p><h4>3. produceState</h4><p>produceState helps create a state backed by a producer that manages its lifecycle.</p><h4>Example</h4><pre>@Composable<br>fun ClockComponent() {<br>    val time by produceState(initialValue = System.currentTimeMillis()) {<br>        while (true) {<br>            delay(1000L)<br>            value = System.currentTimeMillis()<br>        }<br>    }<br><br>    Text(&quot;Current time: ${Date(time)}&quot;)<br>}</pre><p>In this example, produceState creates a state that updates every second to show the current time.</p><h4>4. snapshotFlow</h4><p>snapshotFlow converts a snapshot state to a flow.</p><h4>Example</h4><pre>@Composable<br>fun MySnapshotFlowComponent() {<br>    val count = remember { mutableStateOf(0) }<br><br>    LaunchedEffect(Unit) {<br>        snapshotFlow { count.value }<br>            .collect { newValue -&gt;<br>                Log.d(&quot;MySnapshotFlowComponent&quot;, &quot;Count: $newValue&quot;)<br>            }<br>    }<br><br>    Button(onClick = { count.value++ }) {<br>        Text(&quot;Increment&quot;)<br>    }<br>}</pre><p>Here, snapshotFlow creates a flow from count and logs the new value every time it changes.</p><h3>Conclusion</h3><p>When working with Jetpack Compose, choosing the right effect handler is crucial:</p><ul><li><strong>Suspend Effect Handlers (LaunchedEffect, rememberCoroutineScope)</strong>: Use these when you need to perform tasks that involve suspending functions, like network requests or long-running operations. They are coroutine-based and handle asynchronous tasks efficiently.</li><li><strong>Non-Suspend Effect Handlers (DisposableEffect, SideEffect)</strong>: Use these for tasks that don’t involve suspending functions but still require lifecycle-aware handling, such as setting up and tearing down listeners or logging data.</li><li><strong>Side Effect States (rememberUpdatedState, derivedStateOf, produceState, snapshotFlow)</strong>: These help manage state changes and dependencies within your composables, ensuring your UI reacts correctly to state updates.</li></ul><p>Understanding and using these tools effectively will help you write more efficient, maintainable, and reactive UI code in Jetpack Compose. Happy composing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b65ea07b3ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/jetpack-compose-simplified-mastering-kotlin-scopes-with-effect-handlers-and-side-effects-9b65ea07b3ce">Jetpack Compose Simplified: Mastering Kotlin Scopes with Effect Handlers and Side Effects</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dispatchers.IO Explained: Supercharge Your Android App’s Performance]]></title>
            <link>https://medium.com/devjoint/dispatchers-io-explained-supercharge-your-android-apps-performance-14761b915e6b?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/14761b915e6b</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 17:43:23 GMT</pubDate>
            <atom:updated>2024-07-17T17:43:23.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuo4cfHci-7Vy1T7I0tsbg.jpeg" /></figure><p>In Android development, when we use Kotlin Coroutines for managing background tasks, we often use Dispatchers.IO for input/output (I/O) operations. Let&#39;s break down why we do this and what&#39;s special about Dispatchers.IO.</p><h3>What is Dispatchers.IO?</h3><p>Dispatchers.IO is a special coroutine dispatcher provided by Kotlin Coroutines designed for I/O operations like reading from or writing to a file, making network requests, or interacting with a database.</p><h3>Why use Dispatchers.IO?</h3><ol><li><strong>Optimized for I/O operations</strong>: Dispatchers.IO is optimized to handle tasks that involve I/O operations. These operations are generally slower and involve waiting (like waiting for a response from a network or a hard drive), so they don&#39;t need to run on the main thread or a CPU-intensive thread.</li><li><strong>Offloading from the Main Thread</strong>: The main thread is responsible for updating the UI and handling user interactions. If you perform slow operations like reading a large file or making a network request on the main thread, the app will freeze, and the user will have a bad experience. Using Dispatchers.IO ensures that these operations are performed on a background thread, keeping the main thread free for UI updates.</li><li><strong>Efficient Resource Usage</strong>: Dispatchers.IO uses a pool of threads that are reused for different I/O tasks. This is more efficient than creating a new thread for each I/O operation, saving system resources and improving performance.</li></ol><h3>Example Usage</h3><p>Here’s a simple example to illustrate the use of Dispatchers.IO in an Android app:</p><h4>Without Coroutines</h4><pre>// Simulating a network request on the main thread (Not recommended)<br>fun fetchData() {<br>    val data = makeNetworkRequest() // This might take a long time<br>    // Update UI with data<br>}</pre><p>In this example, makeNetworkRequest() runs on the main thread, potentially freezing the UI.</p><h4>With Coroutines and Dispatchers.IO</h4><pre>import kotlinx.coroutines.*<br><br>fun fetchData() {<br>    CoroutineScope(Dispatchers.Main).launch {<br>        // Switch to IO context for network request<br>        val data = withContext(Dispatchers.IO) {<br>            makeNetworkRequest() // This runs on a background thread<br>        }<br>        // Back to Main context to update UI<br>        updateUI(data)<br>    }<br>}<br><br>suspend fun makeNetworkRequest(): String {<br>    // Simulating a long network request<br>    delay(2000)<br>    return &quot;Data from network&quot;<br>}<br><br>fun updateUI(data: String) {<br>    // Update the UI with the fetched data<br>}</pre><p>In this example:</p><ol><li><strong>CoroutineScope(Dispatchers.Main).launch { ... }</strong>: Starts a coroutine in the Main thread context for UI-related tasks.</li><li><strong>withContext(Dispatchers.IO) { ... }</strong>: Switches the coroutine context to Dispatchers.IO for the network request, ensuring it runs on a background thread.</li><li><strong>updateUI(data)</strong>: Once the network request is completed, the coroutine context switches back to the Main thread to update the UI.</li></ol><h3>Efficient Resource Usage</h3><p>Efficient resource usage is a key benefit of using Dispatchers.IO for I/O operations. Here’s a detailed explanation of how it works and why it&#39;s important.</p><h4>Thread Management</h4><ul><li><strong>Thread Pool</strong>: Dispatchers.IO uses a shared thread pool for executing I/O operations. Instead of creating a new thread for each task, it reuses existing threads. This reduces the overhead associated with thread creation and destruction, leading to more efficient resource usage.</li><li><strong>Scalability</strong>: The thread pool in Dispatchers.IO is designed to handle a large number of concurrent I/O operations. It can dynamically adjust the number of threads based on the workload, ensuring that resources are used efficiently without overwhelming the system.</li></ul><h4>Non-Blocking I/O</h4><ul><li><strong>Non-Blocking Operations</strong>: I/O operations typically involve waiting for external resources (like a network response or file system read/write). During this waiting period, threads in Dispatchers.IO can perform other tasks instead of sitting idle, thanks to non-blocking I/O.</li><li><strong>Context Switching</strong>: Non-blocking I/O reduces the need for frequent context switching between threads. This minimizes CPU overhead and improves performance, as context switching can be costly in terms of time and resources.</li></ul><h3>Example Comparison</h3><p>Here’s a comparison to illustrate the efficiency of using Dispatchers.IO versus creating separate threads for each I/O operation:</p><p><strong>Using Separate Threads (Inefficient)</strong></p><pre>fun fetchData() {<br>    Thread {<br>        val data = makeNetworkRequest()<br>        runOnUiThread {<br>            updateUI(data)<br>        }<br>    }.start()<br>}<br><br>fun makeNetworkRequest(): String {<br>    // Simulate a long network request<br>    Thread.sleep(2000)<br>    return &quot;Data from network&quot;<br>}</pre><p>In this example:</p><ul><li>Each fetchData() call creates a new thread, which consumes additional memory and processing power.</li><li>Frequent thread creation and destruction lead to increased overhead and potential performance issues.</li></ul><p><strong>Using </strong><strong>Dispatchers.IO (Efficient)</strong></p><pre>import kotlinx.coroutines.*<br><br>fun fetchData() {<br>    CoroutineScope(Dispatchers.Main).launch {<br>        val data = withContext(Dispatchers.IO) {<br>            makeNetworkRequest()<br>        }<br>        updateUI(data)<br>    }<br>}<br><br>suspend fun makeNetworkRequest(): String {<br>    // Simulate a long network request<br>    delay(2000)<br>    return &quot;Data from network&quot;<br>}</pre><p>In this example:</p><ul><li>The coroutine uses Dispatchers.IO to perform the network request on a background thread from the shared thread pool.</li><li>Threads are reused for multiple I/O operations, reducing the overhead of thread management.</li><li>The system dynamically adjusts the number of threads based on the workload, ensuring efficient resource usage.</li></ul><h3>Statistics and Comparison</h3><p>To understand the benefits of using Dispatchers.IO, let&#39;s look at some hypothetical statistics and compare their usage with the approach of creating separate threads for each I/O operation.</p><h4>Scenario Setup</h4><ul><li><strong>Task</strong>: Simulate a network request that takes 2 seconds to complete.</li><li><strong>Number of Tasks</strong>: 100 concurrent network requests.</li><li><strong>System Resources</strong>: CPU with 8 cores, 16 GB RAM.</li></ul><h4>Without Dispatchers.IO</h4><p>When creating separate threads for each I/O operation, the system handles 100 network requests concurrently.</p><ul><li><strong>Thread Creation Overhead</strong>: Each thread creation can take a few milliseconds and consumes memory (stack size, typically 1MB per thread).</li><li><strong>Time per thread creation:</strong> ~5 milliseconds.</li><li><strong>Memory per thread:</strong> ~1MB.</li><li><strong>Total Time for Thread Creation</strong>: 100×5100 \times 5100×5 milliseconds = 500 milliseconds.</li><li><strong>Total Memory for Threads</strong>: 100×1100 \times 1100×1 MB = 100MB.</li><li><strong>Context Switching Overhead</strong>: With 100 threads, frequent context switching adds significant CPU overhead.</li><li><strong>CPU Utilization</strong>: High due to thread management and context switching.</li><li><strong>Responsiveness</strong>: Main thread might become less responsive due to resource contention.</li></ul><p><strong>Hypothetical Performance</strong></p><ul><li><strong>Average CPU Utilization</strong>: 70–80%</li><li><strong>Memory Usage for Threads</strong>: 100MB</li><li><strong>Average Response Time</strong>: ~2.5 seconds (including thread creation overhead and context switching)</li></ul><h4>With Dispatchers.IO</h4><p>Using Dispatchers.IO, the system handles 100 network requests concurrently using a shared thread pool optimized for I/O operations.</p><ul><li><strong>Thread Pool Management</strong>: Dispatchers.IO uses a dynamic thread pool, efficiently reusing threads.</li><li><strong>Time per thread reuse:</strong> Negligible.</li><li><strong>Memory per thread:</strong> Shared among tasks, much lower overhead.</li><li><strong>Total Time for Thread Management</strong>: Negligible compared to creating new threads.</li><li><strong>Total Memory for Threads</strong>: Significantly lower due to thread reuse.</li><li><strong>Context Switching Overhead</strong>: Reduced due to fewer threads and optimized handling of I/O tasks.</li><li><strong>CPU Utilization</strong>: Lower due to efficient thread management.</li><li><strong>Responsiveness</strong>: The main thread remains highly responsive.</li></ul><p>Hypothetical Performance</p><ul><li><strong>Average CPU Utilization</strong>: 30–40%</li><li><strong>Memory Usage for Threads</strong>: ~20MB (reused threads)</li><li><strong>Average Response Time</strong>: ~2 seconds (minimal overhead)</li></ul><h4>Summary of Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bCU8Ewss1gf4OxIT38JEA.png" /></figure><h3>Conclusion</h3><p>Efficient resource usage in Dispatchers.IO is achieved through:</p><ul><li><strong>Thread Pooling</strong>: Reusing a pool of threads for multiple tasks instead of creating new threads.</li><li><strong>Dynamic Scalability</strong>: Adjusting the number of threads based on workload to balance performance and resource usage.</li><li><strong>Non-Blocking I/O</strong>: Allowing threads to perform other tasks while waiting for I/O operations, minimizing idle time and reducing CPU overhead.</li></ul><p>By leveraging these techniques, Dispatchers.IO ensures that I/O operations are handled efficiently, leading to better performance and resource management in Android applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14761b915e6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/dispatchers-io-explained-supercharge-your-android-apps-performance-14761b915e6b">Dispatchers.IO Explained: Supercharge Your Android App’s Performance</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Android Development: Seamless Interoperability Between Java and Kotlin]]></title>
            <link>https://medium.com/devjoint/mastering-android-development-seamless-interoperability-between-java-and-kotlin-b2d6fd4407f3?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d6fd4407f3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[interoperability]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 11:36:45 GMT</pubDate>
            <atom:updated>2024-07-17T11:36:45.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnAlOkiJ8tyKTL1ckZSOMw.jpeg" /></figure><p>Android handles interoperability between Java and Kotlin smoothly, allowing developers to use both languages in the same project seamlessly. Here’s a detailed yet simple explanation of how this works, along with examples.</p><h3>Understanding Kotlin and Java</h3><p><strong>Java</strong> has been the primary language used in Android development for many years. <strong>Kotlin</strong> is a modern programming language fully interoperable with Java and officially supported by Google for Android development. Kotlin is designed to be more concise and expressive than Java.</p><h3>Key Points of Interoperability</h3><ol><li><strong>Calling Java from Kotlin:<br></strong>Kotlin can directly call Java code. This is possible because Kotlin compiles to JVM bytecode, just like Java. Therefore, both languages can understand and use each other’s classes and methods.</li><li><strong>Calling Kotlin from Java:<br></strong>Java can also call Kotlin code. Kotlin classes and methods are accessible from Java, and Kotlin provides annotations to make interoperability smoother.</li></ol><h3>Examples</h3><h4>Example 1: Calling Java Code from Kotlin</h4><p>Imagine you have a simple Java class:</p><pre>// Java class<br>public class JavaExample {<br>    public void sayHello() {<br>        System.out.println(&quot;Hello from Java!&quot;);<br>    }<br>}</pre><p>You can call this Java class from Kotlin like this:</p><pre>// Kotlin code<br>fun main() {<br>    val javaExample = JavaExample()<br>    javaExample.sayHello() // Outputs: Hello from Java!<br>}</pre><p>In this example, the JavaExample class defined in Java is used directly in Kotlin without any extra steps.</p><h4>Example 2: Calling Kotlin Code from Java</h4><p>Here’s a simple Kotlin class:</p><pre>// Kotlin class<br>class KotlinExample {<br>    fun sayHello() {<br>        println(&quot;Hello from Kotlin!&quot;)<br>    }<br>}</pre><p>You can call this Kotlin class from Java like this:</p><pre>// Java code<br>public class Main {<br>    public static void main(String[] args) {<br>        KotlinExample kotlinExample = new KotlinExample();<br>        kotlinExample.sayHello(); // Outputs: Hello from Kotlin!<br>    }<br>}</pre><p>In this example, the KotlinExample class defined in Kotlin is used directly in Java.</p><h3>Null Safety</h3><p>Kotlin provides null safety by default, which helps in avoiding NullPointerException errors. When interacting with Java, Kotlin handles nulls intelligently:</p><ul><li>If a Java method returns a nullable type, Kotlin treats it as nullable.</li><li>If a Java method returns a non-null type, Kotlin treats it as non-null.</li></ul><h4>Example 3: Null Safety</h4><p>Java method returning nullable type:</p><pre>// Java code<br>public class JavaExample {<br>    public String getNullableString() {<br>        return null;<br>    }<br>}</pre><p>Kotlin handles this gracefully:</p><pre>// Kotlin code<br>fun main() {<br>    val javaExample = JavaExample()<br>    val nullableString: String? = javaExample.nullableString<br>    println(nullableString) // Prints: null<br>}</pre><h3>Extension Functions</h3><p>Kotlin allows adding new functions to existing classes using extension functions, which can also be called from Java.</p><h4>Example 4: Extension Function</h4><p>Kotlin extension function:</p><pre>// Kotlin code<br>fun String.greet() = &quot;Hello, $this!&quot;</pre><p>Calling the extension function from Java:</p><pre>// Java code<br>public class Main {<br>    public static void main(String[] args) {<br>        String message = &quot;Kotlin&quot;.greet();<br>        System.out.println(message); // Outputs: Hello, Kotlin!<br>    }<br>}</pre><h3>Interoperability Annotations</h3><p>Kotlin provides several annotations to help with interoperability, such as @JvmOverloads, @JvmStatic, and @JvmName.</p><h4>Example 5: @JvmOverloads</h4><p>Kotlin function with default parameters:</p><pre>// Kotlin code<br>class KotlinExample {<br>    @JvmOverloads<br>    fun greet(name: String = &quot;World&quot;) {<br>        println(&quot;Hello, $name!&quot;)<br>    }<br>}</pre><p>Calling the function from Java:</p><pre>// Java code<br>public class Main {<br>    public static void main(String[] args) {<br>        KotlinExample kotlinExample = new KotlinExample();<br>        kotlinExample.greet(); // Outputs: Hello, World!<br>        kotlinExample.greet(&quot;Java&quot;); // Outputs: Hello, Java!<br>    }<br>}</pre><h3>Using KClass and Class</h3><p>Kotlin uses KClass to represent Kotlin classes, while Java uses Class for its classes. When working with reflection or when you need to obtain a class reference, it&#39;s important to understand how to convert between KClass and Class.</p><h4>Example 6: Converting Between KClass and Class</h4><p>Kotlin Code:</p><pre>import kotlin.reflect.KClass<br><br>class KotlinExample<br><br>fun printClassInfo(kClass: KClass&lt;*&gt;) {<br>    println(&quot;Kotlin class: ${kClass.simpleName}&quot;)<br>    val javaClass: Class&lt;*&gt; = kClass.java<br>    println(&quot;Converted to Java class: ${javaClass.simpleName}&quot;)<br>}<br><br>fun main() {<br>    printClassInfo(KotlinExample::class)<br>}</pre><p>In this example, we have a Kotlin class KotlinExample. The printClassInfo function takes a KClass parameter and prints its name. It then converts the KClass to a Class using the .java property and prints the Java class name.</p><p>Java Code:</p><p>To call this Kotlin function from Java, you can use:</p><pre>// Java code<br>public class Main {<br>    public static void main(String[] args) {<br>        kotlin.reflect.KClass&lt;?&gt; kClass = KotlinExample.class;<br>        KotlinExampleKt.printClassInfo(kClass);<br>    }<br>}</pre><p>In this example, the Java code obtains a reference to the Kotlin class KotlinExample and passes it to the printClassInfo function.</p><h4>Example 7: Using Java Class in Kotlin</h4><p>Conversely, if you have a Java class and you want to use it in Kotlin, you can convert it to a KClass.</p><p>Java Code:</p><pre>// Java class<br>public class JavaExample {<br>    public void sayHello() {<br>        System.out.println(&quot;Hello from Java!&quot;);<br>    }<br>}</pre><p>Kotlin Code:</p><pre>import kotlin.reflect.full.createInstance<br><br>fun useJavaClass(javaClass: Class&lt;*&gt;) {<br>    println(&quot;Java class: ${javaClass.simpleName}&quot;)<br>    val kClass: KClass&lt;*&gt; = javaClass.kotlin<br>    println(&quot;Converted to Kotlin class: ${kClass.simpleName}&quot;)<br><br>    // Using reflection to create an instance and call a method<br>    val instance = kClass.createInstance()<br>    val method = kClass.members.find { it.name == &quot;sayHello&quot; }<br>    method?.call(instance)<br>}<br><br>fun main() {<br>    useJavaClass(JavaExample::class.java)<br>}</pre><p>In this example, the useJavaClass function takes a Class parameter and prints its name. It then converts the Class to a KClass using the .kotlin property and prints the Kotlin class name. Using reflection, it creates an instance of the class and calls the sayHello method.</p><p>Interoperability between Kotlin’s KClass and Java&#39;s Class allows for seamless reflection and type inspection across both languages. Kotlin provides convenient properties and functions to convert between KClass and Class, making it easy to work with classes and their members regardless of their origin.</p><h3>Conclusion</h3><p>Android’s interoperability between Java and Kotlin is seamless, allowing developers to mix both languages in a single project effortlessly. This interoperability includes direct method calls, handling null safety, and using Kotlin-specific features such as extension functions and annotations to ensure smooth integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d6fd4407f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devjoint/mastering-android-development-seamless-interoperability-between-java-and-kotlin-b2d6fd4407f3">Mastering Android Development: Seamless Interoperability Between Java and Kotlin</a> was originally published in <a href="https://medium.com/devjoint">DevJoint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When My Life Got Lock(ed) Down]]></title>
            <link>https://medium.com/@amangarg2395/when-my-life-got-lock-ed-down-870a691fae3c?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/870a691fae3c</guid>
            <category><![CDATA[coronavirus]]></category>
            <category><![CDATA[lockdown]]></category>
            <category><![CDATA[musings]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 18:00:18 GMT</pubDate>
            <atom:updated>2020-08-10T04:55:59.321Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FOJw4CDbtu0jde%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ftitanic-movie-night-OJw4CDbtu0jde&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2FOJw4CDbtu0jde%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/771ec0f3a94a10f52a945e655d7c98ba/href">https://medium.com/media/771ec0f3a94a10f52a945e655d7c98ba/href</a></iframe><p>Do you remember when the Titanic was sinking, and the band kept playing till the end? We are a part of that band. For my entire life, as an IT guy, I have believed that all we need is a 4x4 room with a laptop and a fast internet, that’s all. But, lockdown 2020 forced me to change my beliefs.</p><p><strong>Phase 1: The Shock<br></strong>This was not the first time when humankind had to face the Corona Virus. SARS and MERS are examples of two other coronaviruses that we had to face in the past. But this time it was indeed a shock for everyone, all thanks to the media. I have always been a guy who lives like there is no tomorrow, but being prepared for tomorrow was more of a compulsion than a choice this time. Initially, when our honourable Prime Minister announced lockdown 1, I had already started dreading the monotonous routine, which I had to follow for the next 21 days. Now 21 doesn’t seem much… 😏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*8M5W1y6iJA7JZXGp7ruZ2g.gif" /></figure><p>In a city like Mumbai, wherein local trains, three-seater seats are occupied by four people, and the fifth one asks to adjust one more, where terms such as personal space used to only be a myth, practising social distancing was a nightmare in itself. The rates of masks and sanitisers rocketed overnight, but they became just another necessity, just like <em>Roti, Kapda Aur Makaan</em>. And on top of that, daily calls and messages from concerned family members and relatives added to the burden of surviving the initial lockdown phase.</p><p><strong>Phase 2: The Transition<br></strong>Fortunately, the transition to working remotely was not a very big deal, initially. At my place of work, we were provided with 2 days of remote work. So it was not something which I thought I need to put efforts into. But I was wrong, apparently. When you are far from family, and when the realisation that at the end of the day you and only you have to manage everything hits, working remotely is no more fun. Your sleep routine changes drastically and the weekends no longer hold importance. Even if you manage to save hours in travelling, you will not be able to utilise that saved time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*wXgSrrkoe5B4VystKwbLpQ.gif" /></figure><p>I felt handicapped. My friends and acquaintances in Mumbai, who I would call my extended family, were also out of touch. The concept of personal touch became merely a hypothesis, thanks to the lockdown. One thing my rational mind realised was we never value what we have until it’s gone.</p><p><strong>Phase 3: The Enlightenment<br></strong>Needless to say, this phase was one of the most critical and life-changing phases that I had ever gone through. With the likes of Dalgona Coffee trending on social media platforms like Tik Tok and Instagram, people turning into master chefs and yoga gurus overnight forced me to rethink about how I am spending my time during the quarantine. Fear Of Missing Out, or FOMO, as they say, induced in me a motivation, a much-needed momentum which would change the next 2 weeks of my life in such a way that it would create a long-lasting effect on my life. I’d always heard that change is the only constant, but now I started believing it too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*znAOHtOEHlWMYik4QOQzww.jpeg" /><figcaption><strong>Gratitude</strong> turns what we have into enough</figcaption></figure><p>One very important conclusion which I deciphered during this time was why celebrating your progress is crucial for long-term success: The power of small wins. To keep myself motivated in this time of great depression, I started appreciating smaller things in life. I started imbibing gratitude, even maintained a gratitude journal. With time I realised that it is the small things that matter, and I started appreciating the smaller yet much more valuable aspects of life.</p><p><strong>Phase 4: The Adaptation<br></strong>Time heals everything, and so eventually a phase arrived when everybody got used to what was happening. My case was no different. I learnt how to cook(though I am still not a good cook 😉 ), practised a bit of yoga &amp; <em>pranayama</em> as well, <em>atmanirbhar ban gaya</em>…</p><p>Not that I am a busy bee but when you are in your late twenties, you tend to ignore people or to put in a more humble way, you are so much preoccupied in the cobwebs of your own life that you are not able to spare time for others. But once you get adapted to the fact that it’s the relationships that matter, things start to change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B20JRma4Eggsh24_Q1zyMw.png" /><figcaption>Happiness can be found even in the darkest of times if one only remembers to turn on the light.</figcaption></figure><p>I called up my friends, in fact, video called(yes it’s a big deal for a guy like me), sorted out some old friendships, found some new! Apologised to a lot of people, had fights with equal, if not more! Got overwhelmed by the idea of planning a trip, must have planned at least 3–4 trips, and million-night outs for sure! Basically, it was a roller-coaster of emotions! Life is too small to hold grudges. Stay happy with what you have, don’t crib and don’t forget to value human emotions. Do what you love and go get a hobby, if you don’t have it till now! Worst times make you realise your best assets. And like they say, <em>a smooth sea never made a skilled sailor and I’m glad now I am!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*ZHD3N9CuzYpFKbGVu4JIBg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870a691fae3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s up with Bangalore? Why is it suffering with pathetic traffic woes?]]></title>
            <link>https://medium.com/@amangarg2395/whats-up-with-bangalore-why-is-it-suffering-with-pathetic-traffic-woes-6999448a47a5?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/6999448a47a5</guid>
            <category><![CDATA[carpooling]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[carpool-karaoke]]></category>
            <category><![CDATA[carpool]]></category>
            <category><![CDATA[save-money]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 10:57:08 GMT</pubDate>
            <atom:updated>2018-07-05T10:57:08.787Z</atom:updated>
            <content:encoded><![CDATA[<p>There is no doubt in the fact that Bengaluru can be coined as the Silicon Valley of India. With the likes of Infosys, Wipro, TCS and several other MNCs having their roots in the capital city of Karnataka, the rate of urbanisation in Bangalore is growing exponentially. But these facts are just the tip of the iceberg, the gospel truth lies beneath it.</p><p>According to a study conducted at The Centre of Ecological Sciences IISc, Bengaluru will become a dead city in five years. Unplanned growth will make the city unliveable, the study said.</p><p>Problem?</p><ol><li>Population is exploding, from 65 to 95 lakh in 15 years and counting.</li><li>Traffic Police do not have the numbers to control the ever erupting numbers of vehicles(60 lakh, at last count). Thanks to ill-maintained roads, it takes forever to drive even short distances.</li></ol><p>Solution?</p><p>Unless the government imposes the one child norm in India, there is no solution to the first issue. Also, the maintenance of the architecture is not something which is in our hands. Now the question arises, how to reduce the number of vehicles on road?</p><p>One of the most jam packed routes in Bengaluru is between Doddanekundi to K.R Puram. The area hosts companies like Dell EMC, Samsung, ARM, Visa, AB Inbev and Ericsson. A one way commute to these locations take around 58 minutes.</p><p>Let us look at the interim solution.</p><p>CARPOOLING.</p><p>Yes, car-pooling is something which can be done to counter the problem of traffic in Bengaluru.</p><p>Check this out :</p><p><a href="https://poolmyride.com/search-carpool">https://poolmyride.com/search-ca...</a></p><p>On searching for the carpools between Doddanekundi and K.R Puram, I found out that there are 40 odd relevant carpoolers willing to share ride. How amazing is that?</p><p>I even found two relevant carpools, whose links I am sharing below</p><p><a href="https://www.poolmyride.com/carpool-detail/starts-from/Dodda-Nekkundi-Extension-Doddanekkundi-Bengaluru/going-to/Girinagar-Banashankari-Bengaluru/5a8d652d7f01f6423008a58b">https://www.poolmyride.com/carpo...</a></p><p><a href="https://poolmyride.com/carpool-detail/starts-from/Raghavendra-Circle-Ramamurthy-Nagar-Extension-Bengaluru/going-to/Prestige-Tech-Park-Road-Kadubeesanahalli-Bengaluru/5a6c7c802c10c86f087f6de9">https://poolmyride.com/carpool-d...</a></p><p>And guess what? I am getting a ride for less than 100 bucks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6999448a47a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Has technology left us paralysed?]]></title>
            <link>https://medium.com/@amangarg2395/has-technology-left-us-paralysed-43dfea7e017d?source=rss-37136cad8841------2</link>
            <guid isPermaLink="false">https://medium.com/p/43dfea7e017d</guid>
            <category><![CDATA[fawad-khan]]></category>
            <category><![CDATA[robots]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Aman Garg]]></dc:creator>
            <pubDate>Mon, 31 Jul 2017 06:44:10 GMT</pubDate>
            <atom:updated>2017-07-31T06:44:25.228Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“It has become appallingly obvious that our technology has exceeded our humanity” — <em>Albert Einstein</em></blockquote><p>Technology has started playing too vital a role in our lives. In fact, it won’t be an exaggeration to say that technology has become as indispensable as eating &amp; drinking. Though it is largely a creation of the west, it has clinched its claws in our country too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*sDUyEMQR_14rPOUecH2TjQ.jpeg" /><figcaption>True Story</figcaption></figure><p>Information technology is being used almost by every Indian, and Indian youth is affected the most. Fun fact — Facebook, which has its roots in America, has more users in India in comparison to any other country. As rightly quoted by Facebook creator Mark Zuckerberg,</p><blockquote>“As of 2017, the total population of the world is 7.5 billion. Out of those 7.5 billion people, 2 billion are on Facebook.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*U1IKUVRNiOV35CNMV047Cg.png" /><figcaption>Say what?</figcaption></figure><p>Back in the beginning of the 21st century, internet was considered a privilege. Not only internet, but owning a computer was a big deal. But now, every household has at least one device with internet on it, thanks to Mr. Mukesh Ambani. Had he been a political ruler, he surely would have won!</p><p>There was a time when kids used to play with board games like Money Circle, Ludo, Snakes and Ladders and what not? Now a 12 year old demands an I Phone on his birthday!</p><p><em>Even Superman can’t change into his costume without Phone Booths which have become a thing of the past!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*gRAGQnwcoIuVKEhEGy97OQ.jpeg" /><figcaption>The good old days!</figcaption></figure><p>One thing is for sure, technology has become the necessary evil in today’s time, and the irony is it is both necessary and evil in the same context! Surely it is very difficult for us to survive without getting into some kind of contact with technology, and thus we have made ourself slaves of technology. I believe that with more and more social networking websites coming into existence, it has become a mandatory habit for the youth of our country to showcase themselves in a way which is acceptable to the society but is far far different from their actual personalities. Society matters the most!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*k9DpCCTFPww_bfbXElHhPw.gif" /></figure><p>With girls drooling over the likes of Virat Kohli and Fawad Khan(I agree they are damn attractive!), boys of my generation have shifted their concerns from being casual to grooming themselves, just to find an acceptable place in the society, thanks to technology!</p><p>13 years old girls want to be like the Kardashians, can you believe?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*DxC4Tu84IZvu-8P0mUADhg.gif" /><figcaption>Yeah Yeah Yeah!</figcaption></figure><p>As aptly said by Sir Martin, a royal professor at Cambridge,</p><blockquote>“The journey times are just too great for mortal minds and bodies.</blockquote><blockquote>“If you’re immortal, however, these distances become far less daunting.</blockquote><blockquote>“That journey will be made by robots, not us.”</blockquote><p>I just hope he is wrong this time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Pg82HKNhXTpibMFeGADgHw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43dfea7e017d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>