<?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 Jay Dwivedi on Medium]]></title>
        <description><![CDATA[Stories by Jay Dwivedi on Medium]]></description>
        <link>https://medium.com/@jaidwivedi20?source=rss-96623f28a7ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jkUdSk49v8E0EDvW.</url>
            <title>Stories by Jay Dwivedi on Medium</title>
            <link>https://medium.com/@jaidwivedi20?source=rss-96623f28a7ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:02:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaidwivedi20/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[A comprehensive guide to create an Android Travel App — System Design, Architecture and Server…]]></title>
            <link>https://medium.com/@jaidwivedi20/a-comprehensive-guide-to-create-an-android-travel-app-system-design-architecture-and-server-2bf04c004e6f?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bf04c004e6f</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 11:20:40 GMT</pubDate>
            <atom:updated>2024-06-03T11:20:40.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>A comprehensive guide to create an Android Travel App — System Design, Architecture and Server side design and tools</h3><p>Designing a Travel Portal Android App involves multiple components, including user interface design, backend integration, data storage, security, and performance optimization. Here’s a detailed overview of the system design and architecture for such an app:</p><h3>1. Client-Side Architecture (Android App):</h3><h4>UI/UX Design/Layer</h4><ul><li>User Interface: Use Android’s XML layout files to design the user interface. Leverage Material Design components to create an intuitive and visually appealing interface.</li><li>Navigation: Use Jetpack Navigation Component for managing app navigation and ensuring a smooth user experience.</li></ul><h4>Architecture/Presentation Layer</h4><ul><li>MVVM (Model-View-ViewModel): Implement the MVVM architecture pattern to separate concerns and make the codebase more modular and testable.</li><li>ViewModel: Manages the UI-related data and handles business logic.</li><li>Model: Represents the data layer (network and database operations).</li><li>View: Includes Activities and Fragments which display data and handle user interactions.</li></ul><h4>Networking Layer</h4><ul><li>Retrofit: Use Retrofit for making network requests to the backend services. It’s easy to use and integrates well with other components.</li><li>OkHttp: Use OkHttp for handling HTTP operations, which Retrofit internally uses.</li></ul><h4>Local Data Storage</h4><ul><li>Room Database: Use Room for local data storage and caching.</li><li>SharedPreferences: Use SharedPreferences for storing small amounts of key-value data.</li></ul><h4>Dependency Injection</h4><ul><li>Dagger/Hilt: Use Dagger or Hilt for dependency injection to manage the dependencies efficiently.</li></ul><h4>Third-Party Integrations</h4><ul><li>APIs: Integrate with APIs of airlines, hotels, car rentals, and travel aggregators like Expedia for fetching real-time data and booking services.</li></ul><h3>2. Backend Services:</h3><h4>API Gateway</h4><ul><li>API Gateway: Use an API Gateway to manage API requests, handle routing, and provide security and monitoring.</li></ul><h4>Microservices</h4><ul><li>User Service: Manages user authentication, profiles, and preferences.</li><li>Booking Service: Handles booking operations for flights, hotels, and car rentals.</li><li>Payment Service: Manages payment processing and transactions.</li><li>Search Service: Provides search functionality for flights, hotels, and car rentals.</li><li>Notification Service: Sends notifications to users about bookings, offers, etc.</li></ul><h4>Service Orchestration</h4><ul><li>Kubernetes: Use Kubernetes for container orchestration and managing microservices.</li></ul><h4>Authentication and Authorization</h4><ul><li>OAuth 2.0 / JWT: Implement OAuth 2.0 or JWT for securing APIs and user authentication.</li></ul><h4>Caching</h4><ul><li>Redis/Memcached: Use Redis or Memcached for caching frequently accessed data to improve performance.</li></ul><h4>Message Queue</h4><ul><li>RabbitMQ/Kafka: Use RabbitMQ or Kafka for asynchronous communication between microservices.</li></ul><h3>3. Data Storage:</h3><h4>Databases</h4><ul><li>Relational Database: Use PostgreSQL or MySQL for structured data.</li><li>NoSQL Database: Use MongoDB or Cassandra for unstructured data.</li></ul><h4>Data Warehousing</h4><ul><li>Amazon Redshift/Google BigQuery: Use data warehousing solutions for business intelligence and analytics.</li></ul><h3>4. Infrastructure and Deployment:</h3><h4>Cloud Infrastructure</h4><ul><li>AWS/GCP/Azure: Host backend services and databases on cloud platforms for scalability and reliability.</li></ul><h4>Load Balancing</h4><ul><li>NGINX/AWS ELB: Use load balancers to distribute incoming traffic across multiple instances.</li></ul><h4>Continuous Integration and Deployment (CI/CD)</h4><ul><li>Jenkins/GitLab CI/CircleCI: Implement CI/CD pipelines for automated testing, building, and deployment.</li></ul><h3>5. Monitoring and Logging:</h3><h4>Monitoring</h4><ul><li>Prometheus/Grafana/Datadog: Use monitoring tools to track the health and performance of the application.</li></ul><h4>Logging</h4><ul><li>ELK Stack (Elasticsearch, Logstash, Kibana)/Splunk: Implement centralized logging for aggregating and analyzing logs.</li></ul><h3>6. Security:</h3><h4>Transport Layer Security (TLS)</h4><ul><li>HTTPS: Encrypt communication between the client app and backend services using HTTPS.</li></ul><h4>OWASP Top 10</h4><ul><li>Security Best Practices: Protect against common vulnerabilities like SQL injection, XSS, CSRF, etc.</li></ul><h4>Data Encryption</h4><ul><li>AES: Use encryption techniques like AES for encrypting sensitive data.</li></ul><h3>7. Performance Optimization:</h3><h4>Caching</h4><ul><li>Caching Layers: Cache frequently accessed data at various layers to reduce latency.</li></ul><h4>Content Delivery Network (CDN)</h4><ul><li>Cloudflare/Akamai: Use CDN services to deliver static assets faster.</li></ul><h4>Database Indexing</h4><ul><li>Indexes: Create indexes on frequently queried columns to speed up data retrieval.</li></ul><h4>Content Compression</h4><ul><li>Gzip/Deflate: Compress HTTP responses to reduce bandwidth usage and improve load times.</li></ul><h3>High-Level Architecture Diagram</h3><p>Here is a high-level architecture diagram:</p><pre>-----------------<br>| Android App    |<br>|----------------|<br>| UI Layer       |<br>| ViewModel      |<br>| Repository     |<br>| Retrofit       |<br>| Room DB        |<br>|----------------|<br>-----------------<br>        |<br>        v<br>---------------------------<br>|       API Gateway       |<br>---------------------------<br>        |<br>        v<br>------------------------------<br>|    Backend Microservices    |<br>|-----------------------------|<br>| User Service    Booking Service    Payment Service    Search Service    Notification Service |<br>------------------------------<br>        |         |         |<br>        v         v         v<br>------------------------------<br>| Relational DB | NoSQL DB | Message Queue | Caching Layer |<br>------------------------------</pre><h3>Conclusion</h3><p>Designing a Travel Portal Android App requires a well-thought-out architecture to handle various components like user interface, backend services, data storage, security, and performance. By following best practices and using modern technologies, you can build a robust, scalable, and maintainable app that provides a seamless experience for travelers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bf04c004e6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to FlutterFlow: Benefits and Advantages]]></title>
            <link>https://medium.com/@jaidwivedi20/comprehensive-guide-to-flutterflow-benefits-and-advantages-61ce57a459fa?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ce57a459fa</guid>
            <category><![CDATA[crossplatform-mobile-app]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutterflow]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Thu, 30 May 2024 03:34:32 GMT</pubDate>
            <atom:updated>2024-05-30T03:34:32.023Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>FlutterFlow is an innovative visual application development platform designed to simplify the process of building cross-platform mobile applications using Flutter. This guide explores FlutterFlow, its benefits, and how it stands out compared to traditional Flutter native development. We will also include some sample scenarios to illustrate its practical applications.</p><h3>What is FlutterFlow?</h3><p>FlutterFlow is a no-code platform that leverages Flutter, Google’s UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase. FlutterFlow allows developers and non-developers alike to design, build, and deploy mobile applications without writing extensive code. The platform offers a visual interface to create user interfaces, manage data, and integrate with third-party services, streamlining the development process significantly.</p><h3>Benefits of Using FlutterFlow</h3><h4>1. Ease of Use</h4><p>FlutterFlow provides a drag-and-drop interface, making it accessible to users with varying levels of technical expertise. This visual approach reduces the complexity of coding, allowing users to focus on the design and functionality of the app.</p><h4>2. Rapid Prototyping and Development</h4><p>With its intuitive UI builder and real-time preview features, FlutterFlow enables rapid prototyping. Developers can quickly iterate on designs and see changes instantly, speeding up the development cycle.</p><h4>3. Cross-Platform Development</h4><p>FlutterFlow inherently supports cross-platform development, allowing you to build applications for both iOS and Android from a single codebase. This reduces the time and effort required to maintain separate codebases for different platforms.</p><h4>4. Integration with Firebase</h4><p>FlutterFlow offers seamless integration with Firebase, Google’s comprehensive app development platform. This includes easy setup for authentication, database, storage, and other backend services, enhancing the app’s functionality with minimal effort.</p><h4>5. Customization and Export</h4><p>While FlutterFlow emphasizes no-code development, it also allows exporting the generated Flutter code. This provides the flexibility to customize and extend the app using traditional Flutter development if needed.</p><h3>Advantages Over Flutter Native Development</h3><h4>1. Reduced Development Time</h4><p>FlutterFlow’s visual development environment can significantly reduce the time required to create an app compared to traditional coding. This is especially beneficial for MVPs, prototypes, and simple apps.</p><h4>2. Lower Learning Curve</h4><p>For those new to Flutter or mobile app development, FlutterFlow offers a gentler learning curve. It abstracts much of the complexity associated with coding, making it easier for beginners to get started.</p><h4>3. Collaboration</h4><p>The platform’s visual nature makes it easier for non-developers, such as designers and product managers, to collaborate on the app development process. This can lead to more cohesive and well-designed applications.</p><h4>4. Cost Efficiency</h4><p>By speeding up the development process and lowering the need for specialized coding skills, FlutterFlow can reduce the overall cost of app development. This makes it an attractive option for startups and small businesses.</p><h3>Sample Scenario: Building a Onboarding App</h3><p>Let’s walk through a simple example of creating a To-Do List app using FlutterFlow.</p><h4>Step 1: Project Setup</h4><ul><li>Create a New Project: Start by creating a new project in FlutterFlow and selecting the default template.</li><li>UI Design: Use the drag-and-drop interface to design the main screen. Add a list widget to display tasks, a text field for input, and a button to add tasks.</li></ul><h4>Step 2: Adding Functionality</h4><ul><li>State Management: Define a state variable to hold the state.</li><li>Add Login and signup screen from existing template</li><li>Add onboarding flow from signup</li><li>Add other screen like dashboard or user profile</li><li>Add Logic: This can be done using FlutterFlow’s built-in actions without writing code.</li></ul><h4>Step 3: Firebase Integration</h4><ul><li>Setup Firebase: Connect your FlutterFlow project to Firebase for data persistence. Set up a Firestore collection to store users.</li><li>Login and signup : Done with firebase authentication.</li><li>Sync Data: Configure the app to sync users with Firestore, ensuring that users are stored and retrieved from the cloud.</li></ul><h4>Step 4: Testing and Deployment</h4><ul><li>Preview: Use the real-time preview feature to test the app within FlutterFlow.</li><li>Deploy App: Once satisfied with the app, export the code or directly deploy it to the app stores from FlutterFlow.</li><li>Deploy web: Once satisfied with the web app, publish or directly deploy it to the firebase hosting from FlutterFlow.</li></ul><p><a href="https://bank-customer-onboarding-tgbti8.flutterflow.app/">https://bank-customer-onboarding-tgbti8.flutterflow.app</a></p><h3>Conclusion</h3><p>FlutterFlow presents a compelling solution for building mobile applications efficiently and effectively. Its visual development interface, coupled with the power of Flutter, offers significant advantages over traditional coding approaches. By reducing development time, lowering the learning curve, and facilitating cross-platform development, FlutterFlow stands out as a valuable tool for both novice and experienced developers.</p><p>Whether you’re looking to prototype quickly, reduce costs, or collaborate more effectively with non-developers, FlutterFlow provides a versatile and user-friendly platform to achieve your mobile app development goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ce57a459fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Android App with Kotlin, Coroutine, Flow, Jetpack Compose, Hilt, Retrofit, Room…]]></title>
            <link>https://medium.com/@jaidwivedi20/building-a-modern-android-app-with-kotlin-coroutine-flow-jetpack-compose-hilt-retrofit-room-52a4055562a9?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a4055562a9</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotli]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[retrofit]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 07:34:59 GMT</pubDate>
            <atom:updated>2024-05-29T07:34:59.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Modern Android App with Kotlin, Coroutine, Flow, Jetpack Compose, Hilt, Retrofit, Room Database, and MVVM Architecture</h3><p>In this tutorial, we’ll create a modern Android app that incorporates the latest technologies and best practices. We’ll leverage Kotlin, Coroutines, Flow, Jetpack Compose, Hilt for dependency injection, Retrofit for networking, Room Database for local storage, and MVVM architecture for organizing the code.</p><h3>High-Level Design (HLD)</h3><p>Our app will follow a standard MVVM (Model-View-ViewModel) architecture:</p><ul><li>Model: Represents the data and business logic.</li><li>View: Represents the UI components.</li><li>ViewModel: Acts as a bridge between the View and the Model, handling UI-related logic.</li></ul><p>We’ll use Hilt for dependency injection, Retrofit for network calls, and Jetpack Compose for building UI components. Coroutines will handle asynchronous operations, and Flow will be used for reactive data streams.</p><h3>Project Setup</h3><ol><li>Create a new Android project: Open Android Studio and create a new project with an Empty Activity template.</li><li>Add necessary dependencies:</li><li>Add dependencies for Hilt, Retrofit, Coroutines, Jetpack Compose, and other required libraries in your build.gradle file.</li><li>Set up Hilt: Follow the <a href="https://developer.android.com/training/dependency-injection/hilt-android">official documentation</a> to set up Hilt for dependency injection in your app.</li><li>Set up Retrofit: Set up Retrofit for making API calls to a remote server. Define API interfaces and models for data parsing.</li><li>Set up MVVM Architecture: Create packages for models, views, and viewmodels. Implement the MVVM architecture pattern by defining data models, view models, and UI components.</li><li>Implement Flow and Coroutines: Use Coroutines to handle asynchronous tasks and Flow for reactive data streams. Implement repository classes to fetch data using Coroutines and expose them as Flows.</li><li>Navigation Component: For navigating between screens.</li></ol><p>9. Room Database: For local storage.</p><p>10. Build UI with Jetpack Compose: Design UI components using Jetpack Compose. Create composables for various UI elements and compose them together to build screens.</p><h3>Project Structure</h3><p>Our project structure will follow a modular approach, separating concerns and promoting code reusability. Here’s a high-level overview of the project structure:</p><pre>app<br>|-- src<br>    |-- main<br>        |-- java/com/example/myapp<br>            |-- di                    // Dependency Injection<br>            |-- data                  // Data layer<br>                |-- model            // Data models<br>                |-- remote           // Remote data source (Retrofit)<br>                |-- local            // Local data source (Room Database)<br>                |-- repository       // Repository pattern<br>            |-- ui                    // UI layer<br>                |-- screens          // Jetpack Compose screens<br>                |-- viewmodels       // ViewModels<br>        |-- res</pre><h3>Code Sample</h3><p>Let’s look at a simplified code sample for fetching data from a remote API using Retrofit, Coroutines, Flow, and Hilt:</p><h3>Step-by-Step Implementation</h3><h4>1. Add Dependencies</h4><p>Add the necessary dependencies to your build.gradle file:</p><pre>dependencies {<br>    // Kotlin and Coroutines<br>    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib:1.6.10&quot;<br>    implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0&quot;<br>    implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0&quot;<br><br>    // Retrofit<br>    implementation &quot;com.squareup.retrofit2:retrofit:2.9.0&quot;<br>    implementation &quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;<br><br>    // Room<br>    implementation &quot;androidx.room:room-runtime:2.4.1&quot;<br>    kapt &quot;androidx.room:room-compiler:2.4.1&quot;<br>    implementation &quot;androidx.room:room-ktx:2.4.1&quot;<br><br>    // Hilt<br>    implementation &quot;com.google.dagger:hilt-android:2.38.1&quot;<br>    kapt &quot;com.google.dagger:hilt-android-compiler:2.38.1&quot;<br><br>    // Jetpack Compose<br>    implementation &quot;androidx.compose.ui:ui:1.1.1&quot;<br>    implementation &quot;androidx.compose.material:material:1.1.1&quot;<br>    implementation &quot;androidx.compose.ui:ui-tooling-preview:1.1.1&quot;<br>    implementation &quot;androidx.activity:activity-compose:1.4.0&quot;<br><br>    // ViewModel<br>    implementation &quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1&quot;<br>    implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:2.4.1&quot;<br><br>    // Navigation<br>    implementation &quot;androidx.navigation:navigation-compose:2.4.1&quot;<br><br>    // Hilt for ViewModel<br>    implementation &quot;androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03&quot;<br>    kapt &quot;androidx.hilt:hilt-compiler:1.0.0&quot;<br>}</pre><h4>2. Set up Hilt</h4><p>Enable Hilt by adding the Hilt plugin in your root build.gradle file:</p><pre>buildscript {<br>    ext.hilt_version = &#39;2.38.1&#39;<br>    dependencies {<br>        classpath &quot;com.google.dagger:hilt-android-gradle-plugin:$hilt_version&quot;<br>    }<br>}</pre><p>Apply the Hilt plugin in your app build.gradle file:1. Create Application Class</p><pre>apply plugin: &#39;dagger.hilt.android.plugin&#39;</pre><p>Create the Application class and annotate it with @HiltAndroidApp to enable Hilt dependency injection:</p><pre>// MyApp.kt<br>package com.example.myapp<br><br>import android.app.Application<br>import dagger.hilt.android.HiltAndroidApp<br><br>@HiltAndroidApp<br>class MyApp : Application()</pre><h4>3. Define Data Models</h4><p>Define the data model classes for the API response and Room entity: inside data-&gt;model</p><pre>// User.kt<br>package com.example.myapp.data.model<br><br>import androidx.room.Entity<br>import androidx.room.PrimaryKey<br><br>@Entity(tableName = &quot;users&quot;)<br>data class User(<br>    @PrimaryKey val id: Int,<br>    val name: String,<br>    val email: String<br>)</pre><h4>4. Set up Retrofit</h4><p>Define the API service interface: inside data- remote</p><pre>// UserService.kt<br>package com.example.myapp.data.remote<br><br>import com.example.myapp.data.model.User<br>import retrofit2.http.GET<br><br>interface UserService {<br>    @GET(&quot;users&quot;)<br>    suspend fun getUsers(): List&lt;User&gt;<br>}</pre><p>inside di package create a Object class NetworkModule</p><pre>// NetworkModule.kt<br>package com.example.myapp.di<br><br>import com.example.myapp.data.remote.UserService<br>import dagger.Module<br>import dagger.Provides<br>import dagger.hilt.InstallIn<br>import dagger.hilt.components.SingletonComponent<br>import retrofit2.Retrofit<br>import retrofit2.converter.gson.GsonConverterFactory<br>import javax.inject.Singleton<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object NetworkModule {<br>    @Provides<br>    @Singleton<br>    fun provideRetrofit(): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(&quot;https://jsonplaceholder.typicode.com/&quot;)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideUserService(retrofit: Retrofit): UserService {<br>        return retrofit.create(UserService::class.java)<br>    }<br>}<br><br>//you can  also add your own HTTP clients and interceptor with network security here</pre><p>You can also add your own HTTP clients and interceptors with network security. To read more about this in detail, check out my blog.</p><p><a href="https://medium.com/@jaidwivedi20/securing-mobile-apps-part-3-mobile-application-network-security-retrofit-rest-api-af9fa18ad4ac">Securing Mobile Apps — Part 3: Mobile Application Network Security -Retrofit, REST API</a></p><h4>5. Set up Room</h4><p>Define the DAO and Database classes:</p><pre>// AppDatabase.kt<br>package com.example.myapp.data.local<br><br>import androidx.room.Database<br>import androidx.room.RoomDatabase<br>import com.example.myapp.data.model.User<br><br>@Database(entities = [User::class], version = 1)<br>abstract class AppDatabase : RoomDatabase() {<br>    abstract fun userDao(): UserDao<br>}</pre><pre>// UserDao.kt<br>package com.example.myapp.data.local<br><br>import androidx.room.Dao<br>import androidx.room.Insert<br>import androidx.room.OnConflictStrategy<br>import androidx.room.Query<br>import com.example.myapp.data.model.User<br>import kotlinx.coroutines.flow.Flow<br><br>@Dao<br>interface UserDao {<br>    @Query(&quot;SELECT * FROM users&quot;)<br>    fun getUsers(): Flow&lt;List&lt;User&gt;&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    suspend fun insertAll(users: List&lt;User&gt;)<br>}</pre><p>Provide the Room database instance using Hilt:</p><pre>// DatabaseModule.kt<br>package com.example.myapp.di<br><br>import android.content.Context<br>import androidx.room.Room<br>import com.example.myapp.data.local.AppDatabase<br>import com.example.myapp.data.local.UserDao<br>import dagger.Module<br>import dagger.Provides<br>import dagger.hilt.InstallIn<br>import dagger.hilt.android.qualifiers.ApplicationContext<br>import dagger.hilt.components.SingletonComponent<br>import javax.inject.Singleton<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object DatabaseModule {<br>    @Provides<br>    @Singleton<br>    fun provideDatabase(@ApplicationContext context: Context): AppDatabase {<br>        return Room.databaseBuilder(context, AppDatabase::class.java, &quot;my_database&quot;)<br>            .build()<br>    }<br><br>    @Provides<br>    fun provideUserDao(appDatabase: AppDatabase): UserDao {<br>        return appDatabase.userDao()<br>    }<br>}</pre><h4>6. Implement Repository</h4><p>Implement the UserRepository to handle data operations:</p><pre>// UserRepository.kt<br>interface UserRepository {<br>    fun getUsers(): Flow&lt;List&lt;UserEntity&gt;&gt;<br>    suspend fun refreshUsers()<br>}</pre><pre><br><br><br>// UserRepository.kt<br>package com.example.myapp.data.repository<br><br>import com.example.myapp.data.local.UserDao<br>import com.example.myapp.data.model.User<br>import com.example.myapp.data.remote.UserService<br>import kotlinx.coroutines.flow.Flow<br>import javax.inject.Inject<br><br>class UserRepository @Inject constructor(<br>    private val userService: UserService,<br>    private val userDao: UserDao<br>): UserRepository {<br>    override fun getUsers(): Flow&lt;List&lt;User&gt;&gt; = userDao.getUsers()<br><br>    override suspend fun refreshUsers() {<br>        val users = userService.getUsers()<br>        userDao.insertAll(users)<br>    }<br>}</pre><h4>7. Create ViewModel</h4><p>Create the UserViewModel to handle UI-related data operations:</p><pre>// UserViewModel.kt<br>package com.example.myapp.ui.viewmodels<br><br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.viewModelScope<br>import com.example.myapp.data.model.User<br>import com.example.myapp.data.repository.UserRepository<br>import dagger.hilt.android.lifecycle.HiltViewModel<br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.launch<br>import javax.inject.Inject<br><br>@HiltViewModel<br>class UserViewModel @Inject constructor(<br>    private val userRepository: UserRepository<br>) : ViewModel() {<br>    val users: Flow&lt;List&lt;User&gt;&gt; = userRepository.getUsers()<br><br>    fun refreshUsers() {<br>        viewModelScope.launch {<br>            userRepository.refreshUsers()<br>        }<br>    }<br>}</pre><h4>8. Create Compose UI</h4><p>Create a composable function to display the list of users:</p><pre>// UserListScreen.kt<br>package com.example.myapp.ui.screens<br><br>import androidx.compose.foundation.layout.Column<br>import androidx.compose.foundation.lazy.LazyColumn<br>import androidx.compose.foundation.lazy.items<br>import androidx.compose.material.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.collectAsState<br>import androidx.hilt.navigation.compose.hiltViewModel<br>import com.example.myapp.data.model.User<br>import com.example.myapp.ui.viewmodels.UserViewModel<br><br>@Composable<br>fun UserListScreen(userViewModel: UserViewModel = hiltViewModel()) {<br>    val users = userViewModel.users.collectAsState(initial = emptyList())<br><br>    Column {<br>        Text(text = &quot;User List&quot;)<br>        LazyColumn {<br>            items(users.value) { user -&gt;<br>                UserItem(user)<br>            }<br>        }<br>    }<br><br>    LaunchedEffect(Unit) {<br>        userViewModel.refreshUsers()<br>    }<br>}<br>@Composable<br>fun UserItem(user: UserEntity) {<br>    Text(text = user.name)<br>}</pre><h4>9. Set up Main Activity</h4><p>Set up the main activity to use Jetpack Compose and display the UserListScreen:</p><pre>// MainActivity.kt<br>package com.example.myapp<br><br>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import com.example.myapp.ui.screens.UserListScreen<br>import dagger.hilt.android.AndroidEntryPoint<br><br>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            UserListScreen()<br>        }<br>    }<br>}</pre><p>Add AppModule for providing and binding other hilt modules</p><pre>import com.jay.businessaccmgmt.data.RestaurantRepository<br>import com.jay.businessaccmgmt.data.local.dao.ProductDao<br>import com.jay.businessaccmgmt.data.remote.ApiService<br>import com.jay.businessaccmgmt.domain.FirestoreService<br>import dagger.Module<br>import dagger.Provides<br>import dagger.hilt.InstallIn<br>import dagger.hilt.components.SingletonComponent<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideUserRepository(<br>        apiService: ApiService,<br>        userDao: UserDao<br>    ): UserRepository {<br>        return UserRepositoryImpl(apiService, userDao)<br>    }<br> @Provides<br>    fun provideUserViewModel(userRepository: UserRepository)= UserViewModel(repository)<br>}</pre><p>Add <strong>AppComponent</strong> Class in src folder to define hilt component and attached</p><pre>import com.jay.businessaccmgmt.di.AppModule<br>import com.jay.businessaccmgmt.di.NetworkModule<br>import com.jay.businessaccmgmt.di.RepositoryModule<br>import dagger.Component<br>import javax.inject.Singleton<br><br>@Singleton<br>@Component(modules = [AppModule::class, NetworkModule::class, DatabaseModule::class])<br>interface AppComponent {<br><br>    // Inject into MyApp (Application class)<br>    fun inject(application: RestaurantApp)<br><br>    // Other inject methods for activities, fragments, etc.<br>    // e.g., fun inject(activity: MyActivity)<br>}</pre><h3>10. Test Cases</h3><p>Let’s add test cases for the repository, ViewModel, and composable function.</p><h4>10.1 Testing UserRepository</h4><p>We will use JUnit and MockWebServer to test the repository:</p><pre>// UserRepositoryTest.kt<br>package com.example.myapp.data.repository<br><br>import androidx.arch.core.executor.testing.InstantTaskExecutorRule<br>import com.example.myapp.data.local.UserDao<br>import com.example.myapp.data.model.User<br>import com.example.myapp.data.remote.UserService<br>import kotlinx.coroutines.ExperimentalCoroutinesApi<br>import kotlinx.coroutines.flow.collect<br>import kotlinx.coroutines.flow.first<br>import kotlinx.coroutines.runBlocking<br>import kotlinx.coroutines.test.runTest<br>import okhttp3.mockwebserver.MockResponse<br>import okhttp3.mockwebserver.MockWebServer<br>import org.junit.After<br>import org.junit.Before<br>import org.junit.Rule<br>import org.junit.Test<br>import org.mockito.Mockito<br>import org.mockito.Mockito.verify<br>import org.mockito.Mockito.`when`<br><br>@OptIn(ExperimentalCoroutinesApi::class)<br>class UserRepositoryTest {<br><br>    @get:Rule<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    private lateinit var mockWebServer: MockWebServer<br>    private lateinit var userService: UserService<br>    private lateinit var userDao: UserDao<br>    private lateinit var userRepository: UserRepository<br><br>    @Before<br>    fun setUp() {<br>        mockWebServer = MockWebServer()<br>        mockWebServer.start()<br>        userService = Retrofit.Builder()<br>            .baseUrl(mockWebServer.url(https://medium.com/&quot;/&quot;))<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>            .create(UserService::class.java)<br>        userDao = Mockito.mock(UserDao::class.java)<br>        userRepository = UserRepository(userService, userDao)<br>    }<br><br>    @After<br>    fun tearDown() {<br>        mockWebServer.shutdown()<br>    }<br><br>    @Test<br>    fun `fetch users and save to database`() = runTest {<br>        val mockResponse = MockResponse()<br>            .setBody(&quot;[{\&quot;id\&quot;: 1, \&quot;name\&quot;: \&quot;John Doe\&quot;, \&quot;email\&quot;: \&quot;john@example.com\&quot;}]&quot;)<br>        mockWebServer.enqueue(mockResponse)<br><br>        userRepository.refreshUsers()<br><br>        verify(userDao).insertAll(<br>            listOf(User(id = 1, name = &quot;John Doe&quot;, email = &quot;john@example.com&quot;))<br>        )<br>    }<br>}</pre><h4>10.2 Testing UserViewModel</h4><p>We will use JUnit and Mockito to test the ViewModel:</p><pre>// UserViewModelTest.kt<br>package com.example.myapp.ui.viewmodels<br><br>import androidx.arch.core.executor.testing.InstantTaskExecutorRule<br>import com.example.myapp.data.model.User<br>import com.example.myapp.data.repository.UserRepository<br>import kotlinx.coroutines.ExperimentalCoroutinesApi<br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.flow.flow<br>import kotlinx.coroutines.test.runTest<br>import org.junit.Rule<br>import org.junit.Test<br>import org.mockito.Mockito.*<br><br>@OptIn(ExperimentalCoroutinesApi::class)<br>class UserViewModelTest {<br><br>    @get:Rule<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    @Test<br>    fun `fetch users and update LiveData`() = runTest {<br>        val userRepository = mock(UserRepository::class.java)<br>        val users = listOf(User(id = 1, name = &quot;John Doe&quot;, email = &quot;john@example.com&quot;))<br>        `when`(userRepository.getUsers()).thenReturn(flow { emit(users) })<br>        <br>        val userViewModel = UserViewModel(userRepository)<br><br>        userViewModel.refreshUsers()<br><br>        val result = userViewModel.users.value<br>        assert(result == users)<br>    }<br>}</pre><h4>10.3 Testing Compose UI</h4><p>We will use Compose testing libraries to test the composable function:Repository Interface:</p><pre>// UserListScreenTest.kt<br>package com.example.myapp.ui.screens<br><br>import androidx.compose.runtime.collectAsState<br>import androidx.compose.ui.test.junit4.createComposeRule<br>import androidx.lifecycle.ViewModelProvider<br>import androidx.lifecycle.viewmodel.compose.viewModel<br>import androidx.test.ext.junit.runners.AndroidJUnit4<br>import com.example.myapp.data.model.User<br>import com.example.myapp.ui.viewmodels.UserViewModel<br>import dagger.hilt.android.testing.HiltAndroidRule<br>import dagger.hilt.android.testing.HiltAndroidTest<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.StateFlow<br>import org.junit.Before<br>import org.junit.Rule<br>import org.junit.Test<br>import org.junit.runner.RunWith<br><br>@RunWith(AndroidJUnit4::class)<br>@HiltAndroidTest<br>class UserListScreenTest {<br><br>    @get:Rule<br>    val hiltRule = HiltAndroidRule(this)<br><br>    @get:Rule<br>    val composeRule = createComposeRule()<br><br>    private lateinit var viewModel: UserViewModel<br><br>    @Before<br>    fun setUp() {<br>        hiltRule.inject()<br>        viewModel = viewModel()<br>        viewModel = object : UserViewModel() {<br>            private val _users = MutableStateFlow(<br>                listOf(User(id = 1, name = &quot;John Doe&quot;, email = &quot;john@example.com&quot;))<br>            )<br>            override val users: StateFlow&lt;List&lt;User&gt;&gt; get() = _users<br>        }<br>    }<br><br>    @Test<br>    fun userListScreen_displaysUsers() {<br>        composeRule.setContent {<br>            UserListScreen(viewModel)<br>        }<br><br>        composeRule.onNodeWithText(&quot;John Doe&quot;).assertExists()<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a4055562a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering in Kotlin — Part-6- Flow and use cases]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-in-kotlin-part-6-flow-and-use-cases-4acc2c30bd35?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/4acc2c30bd35</guid>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[hot-flow]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 06:01:26 GMT</pubDate>
            <atom:updated>2024-05-29T06:01:26.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering in Kotlin — Part-6- Flow and use cases</h3><p>Kotlin Flow is a powerful asynchronous data stream processing library that brings reactive programming to Kotlin. It allows developers to handle streams of data asynchronously in a more declarative and concise way. Understanding the different types of flows, their characteristics, and appropriate use cases is essential for mastering Kotlin Flow.</p><h3>Types of Flows</h3><h4>1. Cold Flow</h4><ul><li>Description: Cold flows start emitting items when a terminal operator is applied to them, such as collect or toList.</li><li>Behavior: Each collector attached to a cold flow starts its own independent stream of data.</li><li>Every collector start collecting from initial emission and no replay or store mechanism available</li></ul><h4>a. flowOf</h4><ul><li>Description: flowOf is a function that creates a cold flow emitting a fixed set of values sequentially.</li><li>Usage: It is useful when you have a predefined set of values to emit as a flow.</li></ul><pre>import kotlinx.coroutines.flow.flowOf<br>import kotlinx.coroutines.flow.collect<br>import kotlinx.coroutines.runBlocking<br><br>fun main() = runBlocking {<br>    val flow = flowOf(1, 2, 3, 4, 5)<br>    flow.collect { value -&gt;<br>        println(value)<br>    }<br>}</pre><h4>b. flow {}</h4><ul><li>Description: flow {} is a builder function to create custom cold flows emitting values asynchronously.</li><li>Usage: It is suitable for cases where you need to perform asynchronous operations to emit values.</li></ul><pre>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.flow.flow<br>import kotlinx.coroutines.flow.collect<br>import kotlinx.coroutines.runBlocking<br><br>fun main() = runBlocking {<br>    val flow = flow {<br>        for (i in 1..5) {<br>            delay(1000)<br>            emit(i)<br>        }<br>    }<br>    flow.collect { value -&gt;<br>        println(value)<br>    }<br>}</pre><h4>c. Flow&lt;Class&gt;</h4><ul><li>Description: A custom defined flow emitting instances of a specific class.</li><li>Usage: It is used when you want to emit instances of a custom class as a flow.</li></ul><pre>data class User(val id: Int, val name: String)<br><br>fun fetchUsers(): Flow&lt;User&gt; = flow {<br>    // Fetch users from a data source<br>    val users = listOf(User(1, &quot;Alice&quot;), User(2, &quot;Bob&quot;), User(3, &quot;Charlie&quot;))<br>    for (user in users) {<br>        emit(user)<br>    }<br>}</pre><h4>2. Hot Flow</h4><ul><li>Description: Hot flows emit items regardless of whether a collector is attached or not.</li><li>Behavior: Collectors attached to a hot flow receive only items emitted after the collector is attached.</li><li>Start receiving value only after collection start, but we have store or replay for last values(depends on count of replay) fetching or collecting</li><li>We have also buffer for controlling back-pressing</li></ul><p>SharedFlow and StateFlow are both hot flows provided by the Kotlin Coroutines Flow library, but they serve different purposes and have different characteristics. Let&#39;s explore the differences between them and when to use each one:</p><h4>a. StateFlow</h4><ul><li>Purpose: StateFlow is designed for representing a state value as a flow, allowing multiple collectors to observe changes to the state value.</li><li>To convert any flow to a StateFlow, use the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/state-in.html">stateIn</a> intermediate operator.</li></ul><p><strong>Characteristics:</strong></p><ul><li>State Representation: StateFlow represents a single state value that can be observed by collectors. Each collector receives the latest value emitted by the flow and subsequent updates to the state.</li><li>Replay: StateFlow replays the latest emitted value to new collectors, ensuring that all collectors receive the current state value upon subscription.</li></ul><p><strong>Usage:</strong></p><ul><li>Use StateFlow when you need to represent and observe a mutable state value, such as UI state or application state, and ensure that all collectors receive the latest state value.</li></ul><pre>class LatestNewsActivity : AppCompatActivity() {<br>    private val latestNewsViewModel = // getViewModel()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        ...<br>        // Start a coroutine in the lifecycle scope<br>        lifecycleScope.launch {<br>            // repeatOnLifecycle launches the block in a new coroutine every time the<br>            // lifecycle is in the STARTED state (or above) and cancels it when it&#39;s STOPPED.<br>            repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                // Trigger the flow and start listening for values.<br>                // Note that this happens when lifecycle is STARTED and stops<br>                // collecting when the lifecycle is STOPPED<br>                latestNewsViewModel.uiState.collect { uiState -&gt;<br>                    // New value received<br>                    when (uiState) {<br>                        is LatestNewsUiState.Success -&gt; showFavoriteNews(uiState.news)<br>                        is LatestNewsUiState.Error -&gt; showError(uiState.exception)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>class LatestNewsViewModel(<br>    private val newsRepository: NewsRepository<br>) : ViewModel() {<br><br>    // Backing property to avoid state updates from other classes<br>    private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList()))<br>    // The UI collects from this StateFlow to get its state updates<br>    val uiState: StateFlow&lt;LatestNewsUiState&gt; = _uiState<br><br>    init {<br>        viewModelScope.launch {<br>            newsRepository.favoriteLatestNews<br>                // Update View with the latest favorite news<br>                // Writes to the value property of MutableStateFlow,<br>                // adding a new element to the flow and updating all<br>                // of its collectors<br>                .collect { favoriteNews -&gt;<br>                    _uiState.value = LatestNewsUiState.Success(favoriteNews)<br>                }<br>        }<br>    }<br>}<br><br>// Represents different states for the LatestNews screen<br>sealed class LatestNewsUiState {<br>    data class Success(val news: List&lt;ArticleHeadline&gt;): LatestNewsUiState()<br>    data class Error(val exception: Throwable): LatestNewsUiState()<br>}</pre><h4>b. Shared Flow</h4><p>A SharedFlow is a highly-configurable generalization of StateFlow.</p><ul><li>Purpose: SharedFlow is designed for sharing a stream of values among multiple collectors, allowing multiple subscribers to receive the same values emitted by the flow.</li></ul><p><strong>Characteristics:</strong></p><ul><li>Shared Subscription: All collectors of a SharedFlow share the same subscription, meaning that all collectors receive the same values emitted by the flow regardless of when they subscribe.</li><li>Buffered or Unbuffered: It can be configured with a buffer size to buffer emitted values for late subscribers, or it can be unbuffered, causing late subscribers to miss emitted values.</li><li>replay lets you resend a number of previously-emitted values for new subscribers.</li><li>onBufferOverflow lets you specify a policy for when the buffer is full of items to be sent. The default value is BufferOverflow.SUSPEND, which makes the caller suspend. Other options are DROP_LATEST or DROP_OLDEST.</li><li>MutableSharedFlow also has a subscriptionCount property that contains the number of active collectors so that you can optimize your business logic accordingly. MutableSharedFlow also contains a resetReplayCache function if you don&#39;t want to replay the latest information sent to the flow.</li></ul><p><strong>Usage:</strong></p><ul><li>Use SharedFlow when you need to share a stream of values among multiple collectors, and it&#39;s acceptable for late subscribers to miss emitted values.</li></ul><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.MutableSharedFlow<br><br>fun main() = runBlocking {<br>    val sharedFlow = MutableSharedFlow&lt;Int&gt;()<br>    val job = launch {<br>        repeat(5) {<br>            sharedFlow.emit(it)<br>            delay(1000)<br>        }<br>    }<br>    launch {<br>        sharedFlow.collect { value -&gt;<br>            println(&quot;Collector 1 received: $value&quot;)<br>        }<br>    }<br>    launch {<br>        delay(2000) // Late subscriber<br>        sharedFlow.collect { value -&gt;<br>            println(&quot;Collector 2 received: $value&quot;)<br>        }<br>    }<br>    job.join()<br>}</pre><p>You can create a SharedFlow without using shareIn. As an example, you could use a SharedFlow to send ticks to the rest of the app so that all the content refreshes periodically at the same time. Apart from fetching the latest news, you might also want to refresh the user information section with its favorite topics collection. In the following code snippet, a TickHandler exposes a SharedFlow so that other classes know when to refresh its content. As with StateFlow, use a backing property of type MutableSharedFlow in a class to send items to the flow:</p><pre>// Class that centralizes when the content of the app needs to be refreshed<br>class TickHandler(<br>    private val externalScope: CoroutineScope,<br>    private val tickIntervalMs: Long = 5000<br>) {<br>    // Backing property to avoid flow emissions from other classes<br>    private val _tickFlow = MutableSharedFlow&lt;Unit&gt;(replay = 0)<br>    val tickFlow: SharedFlow&lt;Event&lt;String&gt;&gt; = _tickFlow<br><br>    init {<br>        externalScope.launch {<br>            while(true) {<br>                _tickFlow.emit(Unit)<br>                delay(tickIntervalMs)<br>            }<br>        }<br>    }<br>}<br><br>class NewsRepository(<br>    ...,<br>    private val tickHandler: TickHandler,<br>    private val externalScope: CoroutineScope<br>) {<br>    init {<br>        externalScope.launch {<br>            // Listen for tick updates<br>            tickHandler.tickFlow.collect {<br>                refreshLatestNews()<br>            }<br>        }<br>    }<br><br>    suspend fun refreshLatestNews() { ... }<br>    ...<br>}</pre><h3><strong>Making cold flows hot using — </strong>shareIn or stateIn?</h3><p>The first topic we’ll cover is the difference between shareIn and stateIn. The shareIn operator returns a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/">SharedFlow</a> instance whereas stateIn returns a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/index.html">StateFlow</a>.</p><p><strong><em>The main difference between these APIs is that the </em></strong><strong><em>StateFlow interface allows you to access the last emitted value synchronously by reading its </em></strong><strong><em>value property. That’s not the case with </em></strong><strong><em>SharedFlow.</em></strong></p><ul><li><strong><em>The </em></strong><strong><em>shareIn function returns a </em></strong><strong><em>SharedFlow, a hot flow that emits values to all consumers that collect from it.</em></strong></li><li>These APIs can improve performance by sharing the same instance of the flow to be observed by all collectors <strong>instead of creating new instances of the same flow</strong> on-demand.</li></ul><pre>class NewsRemoteDataSource(...,<br>    private val externalScope: CoroutineScope,<br>) {<br>    val latestNews: Flow&lt;List&lt;ArticleHeadline&gt;&gt; = flow {<br>        ...<br>    }.shareIn(<br>        externalScope,<br>        replay = 2,//for buffer the event last 2<br>        started = SharingStarted.WhileSubscribed()<br>    )<br>}</pre><p>The <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-sharing-started/-while-subscribed.html">WhileSubscribed</a> sharing policy is used to cancel the upstream flow when there are no collectors. In this way, we avoid wasting resources when no one is interested in location updates.</p><p><strong>Caching data</strong></p><p>Our requirements have changed again, and in this case, we don’t need to be <em>always</em> listening for location updates if the app is in the background. However, we need to cache the last emitted item so that the user always sees some data on the screen, even if stale, while getting the current location. For this case, we can use the stateIn operator.</p><pre>class LocationRepository(<br>    private val locationDataSource: LocationDataSource,<br>    private val externalScope: CoroutineScope<br>) {<br>    val locations: Flow&lt;Location&gt; = <br>        locationDataSource.locationsSource.stateIn(externalScope, WhileSubscribed(), EmptyLocation)<br>}</pre><p>Flow.stateIn caches and replays the last emitted item to a new collector.</p><h3>Using Operators and Functions</h3><h4>1. collect</h4><ul><li>Description: The collect function is a terminal operator that collects and processes the emitted values from a flow.</li><li>Usage: It is used to consume values emitted by a flow and perform some action for each emitted value.</li></ul><h4>2. onEach</h4><p>The onEach operator performs an action for each value emitted by the flow without affecting the emitted values. It is an intermediate operator and does not trigger the flow execution.</p><h4>3. map</h4><ul><li>Description: The map operator transforms each emitted value of the flow using a given function.</li><li>Usage: It is used to apply a transformation to each emitted value of the flow before collecting or further processing it.</li></ul><h4>4. filter</h4><ul><li>Description: The filter operator filters the values emitted by the flow based on a given predicate function.</li><li>Usage: It is used to selectively collect or process only those values from the flow that satisfy the given condition.</li></ul><h4>5. collectAsState</h4><ul><li>Description: The collectAsState function is an extension function for collecting values from a Flow and transforming them into a State object, typically used in Jetpack Compose for managing UI state.</li><li>Usage: It is used to collect values emitted by a flow and update a Compose UI state with the latest emitted value.</li></ul><h4>6. collectLatest</h4><ul><li>Description: The collectLatest function is a terminal operator that collects values from a flow, but only processes the latest value emitted when multiple values are emitted in quick succession.</li><li>Usage: It is useful when you are only interested in the most recent value emitted by the flow and want to skip intermediate values.</li></ul><pre>import kotlinx.coroutines.flow.*<br>import kotlinx.coroutines.runBlocking<br><br>fun main() = runBlocking {<br>    val flow = (1..10).asFlow()<br>        .onEach { println(&quot;Received: $it&quot;) }<br>        .filter { it % 2 == 0 }<br>        .map { it * it }<br>    flow.collect { value -&gt;<br>        println(&quot;Transformed: $value&quot;)<br>    }<br> flow.collectLatest { value -&gt;<br>        println(value)<br>        delay(200) // Simulate processing time<br>    }<br>}<br><br>// collect As state for jetpack compose<br>fun main() = runBlocking {<br>    val state = mutableStateOf(0)<br>    val flow = flow {<br>        for (i in 1..5) {<br>            emit(i)<br>        }<br>    }<br>    state.value = flow.collectAsState().value<br>    println(state.value)<br>}</pre><h3>Use Cases</h3><ol><li>UI Updates: Use flows to observe changes in data and update UI components reactively.</li><li>Network Requests: Use flows to represent asynchronous responses from network requests and process them asynchronously.</li><li>Database Operations: Use flows to query databases asynchronously and handle database updates reactively.</li><li>Event Bus: Use hot flows as an event bus to broadcast events to multiple subscribers.</li></ol><h3>Summary</h3><ul><li>Cold Flows start emitting values when a collector is actively collecting them and emit values sequentially.</li><li>Hot Flows emit values regardless of whether there are active collectors, and they may replay past values to new collectors.</li><li>flowOf and flow {} are examples of cold flows, while MutableStateFlow and Shared Flow are examples of hot flows.</li><li>Cold flows are suitable for emitting a predefined set of values or performing asynchronous operations to emit values sequentially.</li><li>Hot flows, especially MutableStateFlow and shared flows, are commonly used for sharing state or data streams among multiple components or collectors.</li></ul><h3>Conclusion</h3><p>Kotlin Flow provides a flexible and powerful way to handle asynchronous data streams in Kotlin. By understanding the different types of flows, hot and cold flows, and synchronous and asynchronous usage, you can effectively leverage Kotlin Flow to build reactive and responsive applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4acc2c30bd35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering in Kotlin — Part 4-Comprehensive Guide to Kotlin Coroutines]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-in-kotlin-part-4-comprehensive-guide-to-kotlin-coroutines-30f39ec435e3?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f39ec435e3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 04:10:20 GMT</pubDate>
            <atom:updated>2024-05-29T04:10:20.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering in Kotlin — Part 4-Comprehensive Guide to Kotlin Coroutines</h3><p>Kotlin Coroutines provide a powerful and flexible way to handle asynchronous programming. This guide covers essential coroutine concepts, including async, launch, runBlocking, await, supervisorJob, channel, withContext, and more. Additionally, we&#39;ll discuss exception handling and testing in coroutines.</p><h4>Table of Contents</h4><ol><li>Basics of Coroutines</li></ol><ul><li>CoroutineScope</li></ul><p>2. Coroutine Builders</p><ul><li>launch</li><li>async</li><li>runBlocking</li></ul><p>3. Awaiting Results</p><ul><li>await</li><li>awaitAll</li></ul><p>4. Context and Dispatcher Management</p><ul><li>withContext</li><li>Dispatchers</li></ul><p>5. Exception Handling</p><ul><li>try-catch</li><li>supervisorScope</li><li>CoroutineExceptionHandler</li></ul><p>6. Structured Concurrency</p><ul><li>CoroutineScope</li><li>supervisorJob</li></ul><p>7. Share Data between Coroutines</p><ul><li>Shared Mutable State</li><li>Actors</li><li>Reactive Stream</li><li>Channel</li></ul><p>8. Testing Coroutines</p><p>9. Examples and Use Cases</p><h3>1. Basics of Coroutines</h3><p>Coroutines are lightweight threads that allow you to write asynchronous code sequentially. They are managed by the Kotlin Coroutine library, which provides various coroutine builders and scope management tools.</p><h4>CoroutineScope</h4><p>A CoroutineScope is used to launch new coroutines. It keeps track of all the coroutines it launches and can cancel them collectively.</p><h3>2. Coroutine Builders</h3><h4>launch</h4><p>The launch builder is used to start a new coroutine that does not return a result. It is generally used for fire-and-forget tasks.</p><p>The launch builder starts a new coroutine without blocking the current thread. It returns a Job which can be used to manage the coroutine&#39;s lifecycle.</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>     val job = launch {<br>        // This is a coroutine running in parallel with the main thread<br>        delay(1000L)<br>        println(&quot;World!&quot;)<br>    }<br>    println(&quot;Hello,&quot;)<br>    delay(2000L) // This ensures the main thread waits for the coroutine to complete<br>job.join()  // Wait for the coroutine to finish<br>}</pre><h4>async</h4><p>The async builder starts a new coroutine and returns an instance of Deferred, which represents a promise for a future result.</p><p>It is useful for parallel decomposition of work.</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val deferred = async {<br>        // This is a coroutine that returns a result<br>        delay(1000L)<br>        &quot;Hello, World!&quot;<br>    }<br>    println(deferred.await()) // Waits for the result and prints it<br>}</pre><h3>RunBlocking</h3><p>runBlocking is used to start a coroutine and block the current thread until its completion. It is mainly used in main functions and tests.</p><pre>fun main() = runBlocking {<br>    launch {<br>        delay(1000L)<br>        println(&quot;Coroutine&quot;)<br>    }<br>    println(&quot;Hello from main&quot;)<br>}</pre><h3>3. Await and AwaitAll</h3><p>await waits for the result of a single Deferred, while awaitAll waits for the results of multiple Deferred instances.</p><h4>await</h4><p>The await function is used with Deferred objects to get their result in a non-blocking way.</p><h4>awaitAll</h4><p>The awaitAll function is used to await multiple Deferred objects concurrently.</p><pre>fun main() = runBlocking {<br>    val deferred1 = async { delay(1000L); &quot;Result 1&quot; }<br>    val deferred2 = async { delay(2000L); &quot;Result 2&quot; }<br><br>    val result1 = deferred1.await()<br>    val result2 = deferred2.await()<br>    println(&quot;Results: $result1, $result2&quot;)<br><br>    val results = awaitAll(deferred1, deferred2)<br>    println(&quot;Results: $results&quot;)<br>}</pre><h3>4. Context and Dispatchers</h3><h3>withContext</h3><p>The withContext function allows changing the coroutine context for a block of code. It is often used for switching to different dispatchers.</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    withContext(Dispatchers.IO) {<br>        // Perform IO operations<br>        println(&quot;Running on IO dispatcher&quot;)<br>    }<br>}</pre><h3>Dispatchers</h3><p>Dispatchers determine the thread on which a coroutine runs.</p><ul><li>Dispatchers.Main: Runs coroutines on the main thread (used in Android).</li><li>Dispatchers.IO: Optimized for IO operations.</li><li>Dispatchers.Default: Optimized for CPU-intensive work.</li><li>Dispatchers.Unconfined: Starts coroutines in the calling thread but can move to other threads.</li></ul><h3>5. Exception Handling</h3><p>Exception handling in coroutines can be tricky. It’s important to handle exceptions to avoid crashes and unexpected behaviors.</p><h4>a. Using try-catch</h4><p>The simplest way to handle exceptions in coroutines is by using a try-catch block within the coroutine itself. This method works similarly to traditional exception handling in synchronous code.</p><p>Example: try-catch in Coroutines</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val job = launch {<br>        try {<br>            // Simulate an error<br>            throw ArithmeticException(&quot;Division by zero&quot;)<br>        } catch (e: ArithmeticException) {<br>            println(&quot;Caught an ArithmeticException: ${e.message}&quot;)<br>        }<br>    }<br>    job.join()<br>}<br><br></pre><h4>b. Using supervisorScope</h4><p>A supervisorScope allows for the creation of a scope in which child coroutines can fail independently without cancelling the entire scope. This is particularly useful when you want some parts of your application to continue running even if others fail.</p><p>Example: supervisorScope</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    supervisorScope {<br>        val child1 = launch {<br>            try {<br>                delay(1000L)<br>                println(&quot;Child 1 is done&quot;)<br>            } catch (e: CancellationException) {<br>                println(&quot;Child 1 was cancelled&quot;)<br>            }<br>        }<br><br>        val child2 = launch {<br>            delay(500L)<br>            println(&quot;Child 2 is throwing an exception&quot;)<br>            throw RuntimeException(&quot;Exception in Child 2&quot;)<br>        }<br>        <br>        try {<br>            child2.join()<br>        } catch (e: RuntimeException) {<br>            println(&quot;Caught exception: ${e.message}&quot;)<br>        }<br><br>        delay(1100L) // Ensure that Child 1 completes<br>    }<br>    println(&quot;supervisorScope is done&quot;)<br>}</pre><h4>c. Using CoroutineExceptionHandler</h4><p>CoroutineExceptionHandler is used to handle uncaught exceptions in coroutines. It provides a centralized way to manage exceptions that occur within the context of a coroutine.</p><p>Example: CoroutineExceptionHandler</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val handler = CoroutineExceptionHandler { _, exception -&gt;<br>        println(&quot;Caught $exception&quot;)<br>    }<br><br>    val job = GlobalScope.launch(handler) {<br>        throw AssertionError(&quot;Assertion failed&quot;)<br>    }<br>    job.join()<br>}</pre><h3>6. Structured Concurrency</h3><p>Structured concurrency is a design principle in Kotlin Coroutines that ensures that all coroutines are scoped within a particular CoroutineScope, providing a predictable lifecycle and better error handling. This principle helps avoid memory leaks and ensures that coroutines do not run indefinitely or outlive their intended scope.</p><h3>What is CoroutineScope?</h3><p>A CoroutineScope defines the lifecycle of coroutines. All coroutines launched within a scope are children of that scope. When the scope is cancelled, all its children are cancelled too. This helps manage coroutine hierarchies and their lifecycles efficiently.</p><h4>Creating a CoroutineScope</h4><p>A CoroutineScope can be created using the CoroutineScope interface or by extending the CoroutineScope class.</p><pre>import kotlinx.coroutines.*<br><br>class MyScope : CoroutineScope {<br>    private val job = Job()<br>    override val coroutineContext = Dispatchers.Main + job<br><br>    fun doWork() {<br>        launch {<br>            // Coroutine code<br>        }<br>    }<br><br>    fun clear() {<br>        job.cancel()<br>    }<br>}<br><br>fun main() {<br>    val myScope = MyScope()<br>    myScope.doWork()<br>    // Later...<br>    myScope.clear()<br>}</pre><h4>Using supervisorJob</h4><p>A supervisorJob is a special type of job that allows its children to fail independently. This means that the failure of one child does not affect the other children or the supervisor job itself.</p><p>Example: supervisorJob</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val supervisor = SupervisorJob()<br>    val scope = CoroutineScope(coroutineContext + supervisor)<br><br>    val child1 = scope.launch {<br>        try {<br>            delay(1000L)<br>            println(&quot;Child 1 is done&quot;)<br>        } catch (e: CancellationException) {<br>            println(&quot;Child 1 was cancelled&quot;)<br>        }<br>    }<br><br>    val child2 = scope.launch {<br>        delay(500L)<br>        println(&quot;Child 2 is throwing an exception&quot;)<br>        throw RuntimeException(&quot;Exception in Child 2&quot;)<br>    }<br><br>    child2.invokeOnCompletion { cause -&gt;<br>        if (cause is CancellationException) {<br>            println(&quot;Child 2 was cancelled&quot;)<br>        } else {<br>            println(&quot;Child 2 completed with exception: ${cause?.message}&quot;)<br>        }<br>    }<br><br>    delay(1100L) // Ensure that Child 1 completes<br>    println(&quot;Supervisor scope is done&quot;)<br>}</pre><p>In this example, child2 fails with an exception, but child1 continues to run and completes successfully because the supervisor job allows child coroutines to fail independently.</p><h4>Benefits of Structured Concurrency</h4><ol><li>Lifecycle Management: Coroutines are tied to a specific scope, which controls their lifecycle, making it easier to manage and cancel them when they are no longer needed.</li><li>Error Propagation: Exceptions are propagated through the coroutine hierarchy, ensuring that errors are handled appropriately and do not crash the application unexpectedly.</li><li>Resource Management: By structuring coroutines within scopes, you can avoid resource leaks and ensure that resources are cleaned up when the scope is cancelled.</li></ol><h4>Combining CoroutineScope and SupervisorJob</h4><p>Combining CoroutineScope with SupervisorJob provides a powerful way to manage coroutines, allowing for independent failure of child coroutines while maintaining the benefits of structured concurrency.</p><p>Example: CoroutineScope with SupervisorJob</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val supervisor = SupervisorJob()<br>    val scope = CoroutineScope(coroutineContext + supervisor)<br><br>    val child1 = scope.launch {<br>        try {<br>            delay(1000L)<br>            println(&quot;Child 1 is done&quot;)<br>        } catch (e: CancellationException) {<br>            println(&quot;Child 1 was cancelled&quot;)<br>        }<br>    }<br><br>    val child2 = scope.launch {<br>        delay(500L)<br>        println(&quot;Child 2 is throwing an exception&quot;)<br>        throw RuntimeException(&quot;Exception in Child 2&quot;)<br>    }<br><br>    child2.invokeOnCompletion { cause -&gt;<br>        if (cause != null) {<br>            println(&quot;Child 2 completed with exception: ${cause.message}&quot;)<br>        }<br>    }<br><br>    delay(1100L)<br>    println(&quot;Supervisor scope is done&quot;)<br>}</pre><h3>7. Share Data between Coroutines</h3><p>Refer this one</p><p><a href="https://medium.com/@jaidwivedi20/mastering-in-kotlin-part-5-sharing-the-data-between-coroutines-516ecc30afa8">Mastering in Kotlin — Part-5- Sharing The data between coroutines</a></p><h3>8. Testing Coroutines</h3><p>Testing coroutines involves using the runBlockingTest function provided by the kotlinx-coroutines-test library. This allows you to test coroutines in a controlled environment.</p><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.test.runBlockingTest<br>import kotlin.test.*<br><br>class MyTest {<br><br>    @Test<br>    fun testCoroutine() = runBlockingTest {<br>        val deferred = async {<br>            delay(1000L)<br>            &quot;Result&quot;<br>        }<br>        assertEquals(&quot;Result&quot;, deferred.await())<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f39ec435e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering in Kotlin — Part-5- Sharing The data between coroutines]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-in-kotlin-part-5-sharing-the-data-between-coroutines-516ecc30afa8?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/516ecc30afa8</guid>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 04:07:07 GMT</pubDate>
            <atom:updated>2024-05-29T04:07:07.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering in Kotlin — Part-5- Sharing The data between coroutines</h3><p>Sharing data between coroutines is a common requirement in concurrent programming, and Kotlin provides several approaches to achieve this. Each approach has its own advantages, disadvantages, and best use cases. Let’s explore the various methods of sharing data between coroutines and when to use each approach.</p><p>Share Data between Coroutines</p><ul><li>Shared Mutable State</li><li>Actors</li><li>Reactive Stream</li><li>Channel</li></ul><h3>1. Shared Mutable State</h3><h4>Description:</h4><p>Shared mutable state involves sharing data using shared variables like lists, maps, or other mutable data structures. However, you need to ensure proper synchronization to avoid race conditions and data corruption.</p><pre>import kotlinx.coroutines.*<br><br>val sharedList = mutableListOf&lt;Int&gt;()<br><br>fun main() = runBlocking {<br>    val job1 = launch {<br>        repeat(10) {<br>            sharedList.add(it)<br>            delay(100)<br>        }<br>    }<br>    val job2 = launch {<br>        repeat(10) {<br>            sharedList.add(it + 10)<br>            delay(100)<br>        }<br>    }<br>    job1.join()<br>    job2.join()<br>    println(sharedList)<br>}</pre><h4>When to Use:</h4><ul><li>Suitable for simple scenarios with low contention and small data sets.</li><li>Avoid in complex scenarios with high contention or when multiple coroutines modify the same data concurrently.</li></ul><h3>2. Actors</h3><h4>Description:</h4><p>Actors are a higher-level concurrency primitive that encapsulates state and behavior. They provide a structured way to share mutable state between coroutines while ensuring thread safety.</p><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.channels.actor<br><br>sealed class Message<br>data class Increment(val value: Int) : Message()<br>data class GetTotal(val response: CompletableDeferred&lt;Int&gt;) : Message()<br><br>fun CoroutineScope.counterActor() = actor&lt;Message&gt; {<br>    var total = 0<br>    for (msg in channel) {<br>        when (msg) {<br>            is Increment -&gt; total += msg.value<br>            is GetTotal -&gt; msg.response.complete(total)<br>        }<br>    }<br>}<br><br>fun main() = runBlocking {<br>    val counter = counterActor()<br>    repeat(5) {<br>        counter.send(Increment(1))<br>    }<br>    val response = CompletableDeferred&lt;Int&gt;()<br>    counter.send(GetTotal(response))<br>    println(&quot;Total: ${response.await()}&quot;)<br>    counter.close()<br>}</pre><h4>When to Use:</h4><ul><li>Ideal for scenarios where you need to encapsulate state and behavior within a coroutine.</li><li>Provides built-in message passing and state isolation, making it easier to reason about concurrent code.</li></ul><h3>3. Reactive Streams (e.g., Kotlin Flows)</h3><h4>Description:</h4><p>Reactive streams libraries like Kotlin Flows provide asynchronous data streams and allow for declarative data processing and composition of asynchronous operations.</p><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br>import kotlin.system.measureTimeMillis<br><br>fun main() = runBlocking {<br>    val startTime = System.currentTimeMillis()<br>    (1..5).asFlow()<br>        .map { requestFlow(it) }<br>        .collect { response -&gt;<br>            println(&quot;Response: $response&quot;)<br>        }<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time: ${endTime - startTime} ms&quot;)<br>}<br><br>suspend fun requestFlow(i: Int): String {<br>    delay(1000) // Simulating network request<br>    return &quot;Response $i&quot;<br>}</pre><h4>When to Use:</h4><ul><li>Suitable for asynchronous stream processing and reactive programming.</li><li>Provides operators for transforming, filtering, and combining data streams in a declarative manner.</li></ul><h3>4. Channels</h3><h4>Description:</h4><p>Channels provide a way for coroutines to communicate with each other in a non-blocking, thread-safe manner. They allow both sending and receiving of data between coroutines.</p><h4>a. Creating a Channel</h4><p>You can create a channel using the Channel factory function, specifying the type of elements that the channel will transmit.</p><pre>import kotlinx.coroutines.channels.Channel<br>import kotlinx.coroutines.launch<br>import kotlinx.coroutines.runBlocking<br><br>fun main() = runBlocking {<br>    val channel = Channel&lt;Int&gt;()<br>    val job = launch {<br>        for (i in 1..5) {<br>            channel.send(i)<br>        }<br>        channel.close()<br>    }<br>    for (element in channel) {<br>        println(element)<br>    }<br>    job.join()<br>}</pre><p>In this example, a channel of integers is created, and values 1 through 5 are sent through the channel. The channel is then closed, and the values are received and printed.</p><h4>b. Buffered Channels</h4><p>You can create buffered channels to store a limited number of elements in the channel buffer. This can help in scenarios where the sender and receiver may operate at different speeds.</p><pre>val channel = Channel&lt;Int&gt;(capacity = 5) // Buffer size of 5</pre><h4>c. Channel Operations</h4><p>Channels support various operations like send, receive, close, and offer. These operations allow you to send and receive elements, close the channel, and offer elements without blocking.</p><h4>When to Use:</h4><ul><li>Suitable for producer-consumer scenarios or when you need to stream data between coroutines.</li><li>Provides flow control mechanisms like buffering and backpressure handling.</li></ul><h3>Choosing the Right Approach</h3><ul><li>Shared Mutable State: Use for simple scenarios with low contention and small data sets. Avoid in complex scenarios with high contention.</li><li>Channels: Ideal for producer-consumer scenarios or streaming data between coroutines.</li><li>Actors: Use when you need to encapsulate state and behavior within a coroutine and ensure thread safety.</li><li>Reactive Streams: Suitable for asynchronous stream processing and reactive programming, especially in UI or network-related tasks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516ecc30afa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveData vs Flow in Android Development]]></title>
            <link>https://medium.com/@jaidwivedi20/livedata-vs-flow-in-android-development-923aaef74f26?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/923aaef74f26</guid>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 02:45:26 GMT</pubDate>
            <atom:updated>2024-05-29T05:38:27.327Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>LiveData and Flow are both tools used for data observation in Android, but they serve slightly different purposes and have different characteristics. Below, we compare them, provide examples, and discuss their pros and cons to help determine the best cases for their use.</p><h3>LiveData</h3><p>LiveData is a lifecycle-aware data holder that is designed to hold data that can be observed within a given lifecycle. It’s part of the Android Architecture Components.</p><h4>Pros</h4><ol><li>Lifecycle Awareness: Automatically respects the lifecycle of UI components, such as activities and fragments.</li><li>Easy to Use: Simple API that’s easy to use and understand.</li><li>No Memory Leaks: Observer removal is handled automatically when the lifecycle is destroyed.</li><li>Built-in Support: Part of Android Architecture Components, which means it has strong support and integration with other components.</li></ol><h4>Cons</h4><ol><li>Limited to Main Thread: By default, LiveData operates on the main thread. It requires extra work to handle background threads.</li><li>Single Observer Notion: Not ideal for scenarios where you need to emit data to multiple consumers concurrently.</li></ol><h4>Best Use Cases</h4><ul><li>UI-related data that needs to be lifecycle-aware.</li><li>Simple data observation scenarios.</li><li>Cases where the data source is directly tied to the UI lifecycle.</li><li>When working within the Android ViewModel and Lifecycle framework for typical MVVM architecture.</li></ul><p>LiveData is designed for simple, lifecycle-aware observable patterns. When using LiveData, you often encounter setValue and postValue, which are methods used to update the data.</p><p>setValue:</p><ul><li>Used to set a new value to the LiveData object.</li><li>Must be called from the main thread.</li><li>Immediately updates the LiveData’s observers.</li></ul><pre>// ViewModel class<br>class MyViewModel : ViewModel() {<br>    private val _data = MutableLiveData&lt;String&gt;()<br>    val data: LiveData&lt;String&gt; get() = _data<br><br>    fun updateData(newData: String) {<br>        _data.value = newData  // Must be called on the main thread<br>    }<br>}<br><br>// Usage in Activity or Fragment<br>viewModel.data.observe(this, Observer { updatedData -&gt;<br>    // Update the UI with the new data<br>    textView.text = updatedData<br>})<br><br>viewModel.updateData(&quot;Hello, LiveData with setValue&quot;)</pre><p>postValue:</p><ul><li>Can be called from any thread.</li><li>Posts a task to the main thread to set the given value.</li><li>Useful when updating LiveData from a background thread.</li></ul><pre>// ViewModel class<br>class MyViewModel : ViewModel() {<br>    private val _data = MutableLiveData&lt;String&gt;()<br>    val data: LiveData&lt;String&gt; get() = _data<br><br>    fun updateDataFromBackgroundThread(newData: String) {<br>        // This can be called from a background thread<br>        _data.postValue(newData)<br>    }<br>}<br><br>// Usage in Activity or Fragment<br>viewModel.data.observe(this, Observer { updatedData -&gt;<br>    // Update the UI with the new data<br>    textView.text = updatedData<br>})<br><br>// Simulate background update<br>Thread {<br>    viewModel.updateDataFromBackgroundThread(&quot;Hello, LiveData with postValue&quot;)<br>}.start()</pre><h3>Flow</h3><p>Flow is part of Kotlin Coroutines and is designed to handle asynchronous stream of values. It’s a reactive programming model, similar to RxJava, and provides more flexibility than LiveData.</p><h4>Backpressure Handling</h4><p>Backpressure occurs when a data producer generates items faster than a consumer can process them. Flow provides operators to manage backpressure:</p><ol><li>Buffering: Allows the consumer to keep up by buffering items.</li><li>Conflating: Merges emitted values to ensure the consumer processes only the latest value.</li><li>Dropping: Drops items when the buffer is full.</li><li>Latest: Keeps only the latest value in the buffer.</li></ol><h4>Pros</h4><ol><li>Asynchronous Data Streams: Supports asynchronous data streams natively.</li><li>Backpressure Handling: Better handling of backpressure.</li><li>Multiple Collectors: Can handle multiple collectors easily.</li><li>Coroutines Integration: Seamless integration with Kotlin coroutines for handling background tasks.</li></ol><h4>Cons</h4><ol><li>Lifecycle Management: Requires more effort to handle lifecycle management compared to LiveData.</li><li>Complexity: Slightly more complex API which might be overkill for simple scenarios.</li></ol><h4>Best Use Cases</h4><ul><li>Handling streams of data, such as network responses or database queries.</li><li>Scenarios requiring backpressure support and multiple collectors.</li><li>Cases where you need more control over threading and asynchronous operations.</li><li>When working with Kotlin coroutines for more complex data handling and background processing.</li></ul><pre>// Repository class<br>class MyRepository {<br>    fun fetchData(): Flow&lt;String&gt; = flow {<br>        // Simulate data fetch<br>        emit(&quot;Hello, Flow&quot;)<br>    }<br>}<br><br>// ViewModel class<br>class MyViewModel : ViewModel() {<br>    private val repository = MyRepository()<br><br>    fun getData(): Flow&lt;String&gt; {<br>        return repository.fetchData()<br>    }<br>}<br><br>// Activity or Fragment<br>class MyActivity : AppCompatActivity() {<br><br>    private lateinit var viewModel: MyViewModel<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        viewModel = ViewModelProvider(this).get(MyViewModel::class.java)<br><br>        lifecycleScope.launch {<br>            viewModel.getData().collect { data -&gt;<br>                // Update UI with data<br>                findViewById&lt;TextView&gt;(R.id.textView).text = data<br>            }<br>        }<br>    }<br>}</pre><h3>StateFlow, Flow, and LiveData</h3><p>StateFlow and <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> have similarities. Both are observable data holder classes, and both follow a similar pattern when used in your app architecture.</p><p>Note, however, that StateFlow and <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> do behave differently:</p><ul><li>StateFlow requires an initial state to be passed in to the constructor, while LiveData does not.</li><li>LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not stop collecting automatically. To achieve the same behavior, you need to collect the flow from a Lifecycle.repeatOnLifecycle block.</li></ul><h3>Summary</h3><ul><li>LiveData is best for simple, UI-related data that needs to be lifecycle-aware.</li><li>Flow is best for handling complex asynchronous data streams and offers more control and flexibility, especially when working with Kotlin coroutines.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=923aaef74f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering In Kotlin-Part3- open, object, companion, Singleton, @JvmStatic, and Other Annotations]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-in-kotlin-part3-open-object-companion-singleton-jvmstatic-and-other-annotations-d1a1a34762aa?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a1a34762aa</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[companion]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Mon, 27 May 2024 07:20:29 GMT</pubDate>
            <atom:updated>2024-05-27T07:20:29.337Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin provides various features and annotations to enhance its interoperability with Java and to simplify certain patterns like singletons and companion objects. Here’s an overview of these features with examples.</p><h3>open Keyword</h3><p>In Kotlin, classes and methods are final by default, meaning they cannot be inherited or overridden. To allow inheritance or method overriding, you need to use the open keyword.</p><pre>open class Animal {<br>    open fun makeSound() {<br>        println(&quot;Animal sound&quot;)<br>    }<br>}<br><br>class Dog : Animal() {<br>    override fun makeSound() {<br>        println(&quot;Bark&quot;)<br>    }<br>}<br><br>fun main() {<br>    val dog = Dog()<br>    dog.makeSound() // Output: Bark<br>}</pre><h3>object keyword</h3><p>The object keyword in Kotlin is a concise way to define a singleton pattern, but you can also implement a singleton in a more traditional way if needed.</p><p>object Keyword</p><p>The object keyword in Kotlin is used to create a singleton. A singleton is a class that only has one instance.</p><pre>object Singleton {<br>    fun showMessage() {<br>        println(&quot;Hello from Singleton&quot;)<br>    }<br>}<br><br>fun main() {<br>    Singleton.showMessage() // Output: Hello from Singleton<br>}</pre><p>Use Cases for object:</p><ol><li>Singleton Pattern: To ensure only one instance of the class is created.</li><li>Utility Methods: To group related functions and properties.</li><li>Anonymous Inner Classes: When you need an object of a slight modification of an existing class or interface, often used with interfaces.</li></ol><h3>&#39;companion’ Object</h3><p>A companion object is used to define methods and properties that belong to a class rather than an instance of the class. It&#39;s a way to create static members in Kotlin, as there are no static methods or fields in Kotlin classes. It can access private members of its containing class.</p><pre>class MyClass {<br>    companion object {<br>        fun create(): MyClass = MyClass()<br>    }<br>}<br><br>fun main() {<br>    val myClassInstance = MyClass.create()<br>    println(&quot;Instance created: $myClassInstance&quot;)<br>}</pre><p>Use Cases for companion object:</p><ol><li>Factory Methods: To create instances of the class.</li><li>Static Members: To hold methods or properties that are common to all instances of the class.</li><li>Constants: To define constant values related to the class.</li></ol><h3>@JvmStatic Annotation</h3><p>The @JvmStatic annotation makes a member static in the Java sense. It&#39;s typically used in companion objects or objects to expose static members to Java code.</p><pre>class MyClass {<br>    companion object {<br>        @JvmStatic<br>        fun staticMethod() {<br>            println(&quot;Static method called&quot;)<br>        }<br><br>        fun regularMethod() {<br>            println(&quot;Regular method called&quot;)<br>        }<br>    }<br>}<br><br>fun main() {<br>    MyClass.staticMethod() // Output: Static method called<br>    MyClass.regularMethod() // Output: Regular method called<br>}</pre><h4>@JvmField</h4><p>The @JvmField annotation exposes a property as a field, avoiding the need for getter/setter methods.</p><pre>class Example {<br>    @JvmField<br>    var count = 0<br>}<br><br>fun main() {<br>    val example = Example()<br>    println(example.count) // Direct field access<br>}</pre><h4>@JvmOverloads</h4><p>The @JvmOverloads annotation generates overloads for a function that has default parameter values.</p><pre>class Example {<br>    @JvmOverloads<br>    fun greet(name: String = &quot;World&quot;) {<br>        println(&quot;Hello, $name!&quot;)<br>    }<br>}<br><br>fun main() {<br>    val example = Example()<br>    example.greet() // Output: Hello, World!<br>    example.greet(&quot;Alice&quot;) // Output: Hello, Alice!<br>}</pre><h4>@JvmName</h4><p>The @JvmName annotation changes the name of the generated Java method or property.</p><pre>class Example {<br>    @JvmName(&quot;renamedFunction&quot;)<br>    fun originalFunction() {<br>        println(&quot;This function has been renamed in Java&quot;)<br>    }<br>}<br><br>fun main() {<br>    val example = Example()<br>    example.originalFunction() // Output: This function has been renamed in Java<br>}</pre><h4>@JvmSuppressWildcards</h4><p>This annotation is used to prevent Kotlin from generating wildcard types in generic signatures for Java interoperability.</p><pre>fun processList(list: List&lt;@JvmSuppressWildcards Any&gt;) {<br>    // Processing list<br>}<br><br>fun main() {<br>    val list: List&lt;String&gt; = listOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)<br>    processList(list) // No wildcards generated<br>}</pre><p>These features and annotations provide powerful tools for writing concise, expressive, and interoperable Kotlin code. They enable you to define class hierarchies, singleton instances, static members, and more, while maintaining seamless compatibility with Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a1a34762aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering In Kotlin-Part2- val, var, const, final, open, conditional and control flow]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-in-kotlin-part2-val-var-const-final-open-conditional-and-control-flow-7e52a59abb97?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e52a59abb97</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Mon, 27 May 2024 07:07:45 GMT</pubDate>
            <atom:updated>2024-05-27T07:07:45.057Z</atom:updated>
            <content:encoded><![CDATA[<p>In Kotlin, conditional and control flow structures allow you to dictate the flow of your program’s execution based on certain conditions. Here’s a detailed look at some of the common control flow constructs in Kotlin with examples:</p><h3>val and var</h3><p>In Kotlin, val and var are used to declare variables.</p><ul><li>val (value) is used to declare read-only (immutable) variables. Once a value is assigned to a val, it cannot be changed.</li><li>var (variable) is used to declare mutable variables. The value of a var can be changed.</li></ul><pre>fun main() {<br>    // Using val<br>    val a = 10<br>    // a = 20 // This will cause a compilation error<br><br>    // Using var<br>    var b = 20<br>    b = 30 // This is allowed<br><br>    println(&quot;a: $a, b: $b&quot;)<br>}</pre><h3>const</h3><p>The const keyword in Kotlin is used to declare compile-time constants. These are immutable values known at compile time and are only allowed at the top level or as object properties.</p><pre>const val PI = 3.14<br><br>fun main() {<br>    println(&quot;PI: $PI&quot;)<br>}</pre><h3>final</h3><p>In Kotlin, every class and method is final by default, meaning they cannot be inherited or overridden. To allow inheritance or method overriding, you need to use the open keyword. However, you can explicitly use final to reinforce that a class or method should not be overridden.</p><pre>open class Base {<br>    open fun show() {<br>        println(&quot;Base show&quot;)<br>    }<br>}<br><br>class Derived : Base() {<br>    final override fun show() {<br>        println(&quot;Derived show&quot;)<br>    }<br>}<br><br>fun main() {<br>    val obj = Derived()<br>    obj.show()<br>}</pre><h3>1. if Expression</h3><p>The if expression in Kotlin is similar to the if statement in other languages, but it can also return a value.</p><h3>2. when Expression</h3><p>The when expression in Kotlin can be used as a replacement for the switch statement in other languages. It is powerful and versatile.</p><pre>fun main() {<br>    val x = 3<br><br>    // Simple when expression<br>    when (x) {<br>        1 -&gt; println(&quot;x is 1&quot;)<br>        2 -&gt; println(&quot;x is 2&quot;)<br>        3 -&gt; println(&quot;x is 3&quot;)<br>        else -&gt; println(&quot;x is unknown&quot;)<br>    }<br><br>    // When used as an expression<br>    val result = when (x) {<br>        1 -&gt; &quot;One&quot;<br>        2 -&gt; &quot;Two&quot;<br>        3 -&gt; &quot;Three&quot;<br>        else -&gt; &quot;Unknown&quot;<br>    }<br>    println(&quot;Result is $result&quot;)<br><br>    // When with multiple conditions<br>    val y = 2<br>    when (y) {<br>        0, 1 -&gt; println(&quot;y is either 0 or 1&quot;)<br>        else -&gt; println(&quot;y is neither 0 nor 1&quot;)<br>    }<br>}</pre><h3>3. for Loop</h3><p>The for loop in Kotlin is used to iterate over ranges, arrays, or other iterable objects.</p><pre>fun main() {<br>    // Iterating over a range<br>    for (i in 1..5) {<br>        println(i)<br>    }<br><br>    // Iterating over an array<br>    val array = arrayOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>    for (element in array) {<br>        println(element)<br>    }<br><br>    // Iterating with indices<br>    for (index in array.indices) {<br>        println(&quot;Element at index $index is ${array[index]}&quot;)<br>    }<br>}</pre><h3>4. while and do-while Loops</h3><p>These loops are used for repeating a block of code as long as a condition is true.</p><pre>fun main() {<br>    var i = 5<br><br>    // While loop<br>    while (i &gt; 0) {<br>        println(i)<br>        i--<br>    }<br><br>    // Do-while loop<br>    var j = 5<br>    do {<br>        println(j)<br>        j--<br>    } while (j &gt; 0)<br>}</pre><h3>5. break and continue</h3><p>These keywords are used to control the flow of loops.</p><h3>6. Labels</h3><p>Labels can be used with break and continue to specify which loop to break or continue.</p><pre>fun main() {<br>    outer@ for (i in 1..3) {<br>        for (j in 1..3) {<br>            if (i == 2 &amp;&amp; j == 2) break@outer<br>            println(&quot;i = $i, j = $j&quot;)<br>        }<br>    }<br><br>    println(&quot;Continue with label:&quot;)<br>    outer@ for (i in 1..3) {<br>        for (j in 1..3) {<br>            if (i == 2 &amp;&amp; j == 2) continue@outer<br>            println(&quot;i = $i, j = $j&quot;)<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e52a59abb97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin — Part 1: Null Safety, Scope Functions, lateinit, and lazy]]></title>
            <link>https://medium.com/@jaidwivedi20/mastering-kotlin-part-1-null-safety-scope-functions-lateinit-and-lazy-ad0894d56d26?source=rss-96623f28a7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0894d56d26</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Jay Dwivedi]]></dc:creator>
            <pubDate>Sun, 26 May 2024 04:03:44 GMT</pubDate>
            <atom:updated>2024-05-26T04:03:44.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Kotlin — Part 1: Null Safety, Scope Functions, lateinit, and lazy</h3><p>Kotlin, the modern programming language developed by JetBrains, is renowned for its expressive syntax and powerful features. Among these, null safety and scope functions stand out as tools that significantly enhance the developer experience. Additionally, lateinit and lazy provide sophisticated ways to handle initialization. In this article, we&#39;ll delve into these features with detailed explanations and examples.</p><h4>Null Safety</h4><p>One of the most lauded features of Kotlin is its null safety, which helps developers avoid the dreaded NullPointerException (NPE). Kotlin’s type system distinguishes between nullable and non-nullable types, which is crucial in preventing null-related errors.</p><p>Non-Nullable Types: In Kotlin, a variable cannot hold a null value by default. For example:</p><pre>var name: String = &quot;Kotlin&quot;<br>name = null // This will cause a compile-time error</pre><p>Nullable Types: To allow a variable to hold a null value, you append a question mark ? to its type:</p><pre>var name: String? = &quot;Kotlin&quot;<br>name = null // This is allowed</pre><p>Safe Call Operator ?.: When accessing a property or calling a method on a nullable variable, you use the safe call operator ?. to prevent NPE:</p><pre>val length: Int? = name?.length</pre><p>If name is null, length will also be null, avoiding an exception.</p><p>Elvis Operator ?:: The Elvis operator provides a default value in case the expression on its left side is null:</p><pre>val length: Int = name?.length ?: 0</pre><p>If name is null, length will be assigned 0.</p><p>Safe Cast Operator as?: This operator attempts to cast a value to a specific type, returning null if the cast is not possible:</p><pre>val number: Int? = someObject as? Int</pre><p>Non-Null Assertion !!: If you&#39;re certain that a nullable variable is not null, you can use the non-null assertion operator !!:</p><pre>val length: Int = name!!.length</pre><p>However, use this cautiously, as it will throw an NPE if the variable is null.</p><h4>Scope Functions</h4><p>Scope functions let you execute a block of code within the context of an object. Kotlin provides five scope functions: let, run, with, apply, and also. Each has its own use case and suits different scenarios.</p><p>let: Used to execute a block of code on the result of a nullable expression:</p><pre>val length = name?.let {<br>    println(&quot;Name is $it&quot;)<br>    it.length<br>}</pre><p>run: Used when you want to execute a block of code and return a result:</p><pre>val result = run {<br>    val name = &quot;Kotlin&quot;<br>    name.length<br>}</pre><p>with: Applies to an object and returns a result, commonly used for initializing objects:</p><pre>val builder = StringBuilder()<br>val message = with(builder) {<br>    append(&quot;Hello, &quot;)<br>    append(&quot;world!&quot;)<br>    toString()<br>}</pre><p>apply: Useful for configuring objects. It returns the object itself:</p><pre>val person = Person().apply {<br>    name = &quot;John&quot;<br>    age = 30<br>}</pre><p>also: Similar to apply, but returns the object itself and is often used for side effects:</p><pre>val person = Person().also {<br>    it.name = &quot;John&quot;<br>    it.age = 30<br>}</pre><h4>lateinit and lazy</h4><p>Kotlin provides special properties, lateinit and lazy, for more controlled initialization.</p><p>lateinit: Used with var properties, lateinit allows you to initialize a non-null variable after its declaration. It should only be used with mutable properties:</p><pre>lateinit var name: String<br><br>fun initializeName() {<br>    name = &quot;Kotlin&quot;<br>}<br><br>fun printName() {<br>    if (::name.isInitialized) {<br>        println(name)<br>    } else {<br>        println(&quot;Name is not initialized&quot;)<br>    }<br>}</pre><p>lazy: Used with val properties, lazy initializes the property at the moment it is first accessed. This is useful for expensive operations:</p><pre>val name: String by lazy {<br>    println(&quot;Computing the name&quot;)<br>    &quot;Kotlin&quot;<br>}<br><br>fun main() {<br>    println(name) // &quot;Computing the name&quot; followed by &quot;Kotlin&quot;<br>    println(name) // Just &quot;Kotlin&quot;<br>}</pre><h4>Conclusion</h4><p>Kotlin’s features such as null safety, scope functions, lateinit, and lazy contribute to writing more concise, readable, and safe code. Understanding and effectively utilizing these features can significantly improve your Kotlin programming experience, leading to fewer bugs and more maintainable code. Whether you are a beginner or an experienced developer, mastering these concepts is essential for taking full advantage of Kotlin&#39;s capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0894d56d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>