<?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 Vaghela Mithun on Medium]]></title>
        <description><![CDATA[Stories by Vaghela Mithun on Medium]]></description>
        <link>https://medium.com/@vaghela.mithun?source=rss-55465e48cfa8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5aN-A_jR_r5Bpacf</url>
            <title>Stories by Vaghela Mithun on Medium</title>
            <link>https://medium.com/@vaghela.mithun?source=rss-55465e48cfa8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:42:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaghela.mithun/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[Understanding flatMap Variants in Kotlin Flow]]></title>
            <link>https://medium.com/@vaghela.mithun/understanding-flatmap-variants-in-kotlin-flow-a99eaa041f10?source=rss-55465e48cfa8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a99eaa041f10</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[flatmap]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Vaghela Mithun]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 07:32:56 GMT</pubDate>
            <atom:updated>2025-12-11T07:32:56.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9mfyemH8ZKQ6qNET4xFHA.jpeg" /></figure><h4>flatMapConcat, flatMapMerge, and flatMapLatest</h4><h4><strong>Introduction</strong></h4><p>Reactive programming in Kotlin often involves <strong>transforming streams of data</strong>. When dealing with nested flows (a flow that emits other flows), we need operators to flatten them into a single stream. Kotlin Flow provides three powerful operators — flatMapConcat, flatMapMerge, and flatMapLatest — each with unique behavior. Understanding these differences is crucial for writing efficient, predictable asynchronous code.</p><h4>1. flatMap (Collections)</h4><p>Before diving into flows, let’s recall <strong>flatMap </strong>in collections:</p><ul><li><strong>Behavior:</strong> Transforms each element into a collection and flattens the result.</li><li><strong>Use Case:</strong> Aggregating nested lists into a single list.</li></ul><p><strong>Example: </strong>Fetching user details and then their posts with RxJava</p><pre>val apiService: ApiService = ...<br><br>apiService.getUsers() // returns Observable&lt;List&lt;User&gt;&gt;<br>    .flatMap { users -&gt;<br>        // For each user, fetch their posts<br>        Observable.fromIterable(users)<br>            .flatMap { user -&gt;<br>                apiService.getPosts(user.id) // returns Observable&lt;List&lt;Post&gt;&gt;<br>            }<br>    }<br>    .subscribe({ posts -&gt;<br>        println(&quot;Received posts: $posts&quot;)<br>    }, { error -&gt;<br>        println(&quot;Error: $error&quot;)<br>    })</pre><ul><li><strong>getUsers()</strong> emits a list of users.</li><li><strong>flatMap </strong>converts each user into another observable (<strong>getPosts(user.id)</strong>).</li><li>The results are merged into one observable stream.</li></ul><h4><strong>2. flatMapConcat</strong></h4><p>flatMapConcat is a Kotlin Flow operator that takes each emitted value, transforms it into a new Flow, and then <em>concatenates</em> those flows sequentially—meaning it waits for one flow to finish before starting the next.</p><ul><li><strong>Definition:</strong> It’s an intermediate operator in Kotlin’s Flow API used to <em>flatten</em> flows.</li><li><strong>Behavior:</strong> For every element emitted by the upstream flow, it creates a new flow and collects them <strong>one after another in order</strong>.</li><li><strong>Key Point:</strong> flatMapConcat ensures strict sequential execution</li></ul><p><strong>Example: </strong>Fetching user and their posts using flatMapConcat</p><pre>val usersFlow: Flow&lt;User&gt; = repository.getUsers()<br><br>val postsFlow: Flow&lt;Post&gt; = usersFlow<br>    .flatMapConcat { user -&gt;<br>        repository.getPosts(user.id) // returns Flow&lt;Post&gt;<br>    }<br><br>lifecycleScope.launch {<br>    postsFlow.collect { post -&gt;<br>        println(&quot;Received post: $post&quot;)<br>    }<br>}</pre><ul><li>repository.getUsers() returns a <strong>Flow&lt;User&gt;</strong>.</li><li>This means it will emit a sequence of User objects asynchronously (like a stream of users coming in one by one).</li><li>For <strong>each user</strong> emitted by usersFlow, you call repository.getPosts(user.id).</li><li>That function returns a <strong>Flow&lt;Post&gt;</strong> (all posts belonging to that user).</li><li>flatMapConcat then <strong>concatenates</strong> these flows sequentially</li><li>First, it collects all posts for the first user.</li><li>Only after that flow completes, it moves to the next user’s posts.</li><li>This ensures <strong>order is preserved</strong> and no overlap happens.</li><li>Inside a coroutine (lifecycleScope.launch), you start collecting from postsFlow.</li><li>As posts are emitted (one by one), you print them.</li></ul><h4>Characteristics</h4><ul><li><strong>Sequential execution:</strong> Each inner flow must complete before the next one starts.</li><li><strong>Order preservation:</strong> The results are emitted in the same order as the upstream flow.</li><li><strong>No concurrency:</strong> It doesn’t overlap flows, so it’s simpler but potentially slower if inner flows are long-running.</li></ul><h4><strong>3. flatMapMerge</strong></h4><p>flatMapMerge in Kotlin Flow transforms each emitted value into a new Flow and then <em>merges</em> all those flows concurrently. Unlike flatMapConcat, which processes flows sequentially, flatMapMerge allows multiple inner flows to run in parallel, interleaving their emissions into the final stream</p><ul><li><strong>Definition:</strong> flatMapMerge is an intermediate operator in Kotlin Flow.</li><li><strong>Behavior:</strong> For every element emitted by the upstream flow, it applies a transformation that returns another Flow. All these inner flows are then collected <strong>concurrently</strong> (up to a configurable concurrency limit).</li><li><strong>Result:</strong> The emissions from different flows are merged together into a single Flow, potentially interleaving values.</li></ul><p><strong>Example: </strong>Let’s consider a scenario where we want to <strong>search </strong>users and posts <strong>in parallel</strong> using flatMapMerge.</p><h4>Repository</h4><p>Suppose you’re working with two separate APIs: one that provides user data and another that provides post data. To organize these calls, you can create a SearchRepository class that exposes two methods—searchUsers() and searchPosts()—to fetch data from the respective APIs.</p><pre>class SearchRepository(private val apiService: ApiService) {<br><br>    fun searchUsers(query: String): Flow&lt;List&lt;User&gt;&gt; = flow {<br>        delay(1000) // simulate network delay<br>        emit(apiService.searchUsers(query))<br>    }<br><br>    fun searchPosts(query: String): Flow&lt;List&lt;Post&gt;&gt; = flow {<br>        delay(1500) // simulate network delay<br>        emit(apiService.searchPosts(query))<br>    }<br>}</pre><h4>ViewModel</h4><p>Create a SearchViewModel that depends on SearchRepository to perform searches for both users and posts. By using flatMapMerge, we can execute these two searches <strong>in parallel</strong>, allowing results from users and posts to be fetched concurrently and merged into a single flow.</p><pre>class SearchViewModel(private val repository: SearchRepository) : ViewModel() {<br><br>    private val _searchQuery = MutableStateFlow(&quot;&quot;)<br>    val searchQuery: StateFlow&lt;String&gt; = _searchQuery<br><br>    val searchResults: Flow&lt;SearchResult&gt; = searchQuery<br>        .debounce(300)<br>        .filter { it.isNotBlank() }<br>        .flatMapMerge { query -&gt;<br>            merge(<br>                repository.searchUsers(query).map { SearchResult.Users(it) },<br>                repository.searchPosts(query).map { SearchResult.Posts(it) }<br>            )<br>        }<br>        .flowOn(Dispatchers.IO)<br><br>    fun updateQuery(query: String) {<br>        _searchQuery.value = query<br>    }<br>}<br><br>sealed class SearchResult {<br>    data class Users(val users: List&lt;User&gt;) : SearchResult()<br>    data class Posts(val posts: List&lt;Post&gt;) : SearchResult()<br>}</pre><ul><li>_searchQuery is a <strong>MutableStateFlow</strong> holding the current search text (initially empty).</li><li>searchQuery is the <strong>read-only StateFlow</strong> exposed to observers (UI can collect it but not modify it).</li><li>This is a reactive way to handle search input.</li><li>debounce(300): Waits 300ms after the last input before emitting and prevents firing searches on every keystroke (useful for search bars).</li><li>filter { it.isNotBlank() }: Ignores empty queries and ensures only meaningful search strings trigger API calls.</li><li>flatMapMerge { query -&gt; ... }: For each query, it starts multiple flows <strong>concurrently</strong>. It will merges results from: repository.searchUsers(query) → returns Flow&lt;List&lt;User&gt;&gt; repository.searchPosts(query) → returns Flow&lt;List&lt;Post&gt;&gt;</li><li>Each result is wrapped into a SearchResult sealed class variant: SearchResult.Users(it) and SearchResult.Posts(it)</li><li>merge(...): Combines both flows into a single flow. Results from users and posts can arrive interleaved (parallel execution).</li><li>flowOn(Dispatchers.IO): Ensures the flow runs on the <strong>IO dispatcher</strong> (good for network calls).</li></ul><h4>Activity/Fragment</h4><p>You can implement either an Activity or a Fragment to handle the search feature. Use an EditText to capture the user’s input, and display the search results in a RecyclerView for a clean, scrollable list presentation.</p><pre>class SearchFragment : Fragment() {<br><br>    private val viewModel: SearchViewModel by viewModels {<br>        SearchViewModelFactory(SearchRepository(UserApi(), PostApi()))<br>    }<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        val searchInput = view.findViewById&lt;EditText&gt;(R.id.searchInput)<br>        val resultsList = view.findViewById&lt;RecyclerView&gt;(R.id.resultsList)<br><br>        val adapter = ResultsAdapter()<br>        resultsList.adapter = adapter<br><br>        lifecycleScope.launch {<br>            viewModel.searchResults.collect { result -&gt;<br>                when (result) {<br>                    is SearchResult.Users -&gt; adapter.submitUsers(result.users)<br>                    is SearchResult.Posts -&gt; adapter.submitPosts(result.posts)<br>                }<br>            }<br>        }<br><br>        searchInput.addTextChangedListener { text -&gt;<br>            viewModel.updateQuery(text.toString())<br>        }<br>    }<br>}</pre><h4>Execution Flow Example</h4><ol><li>User types &quot;android&quot;.</li><li>After 300ms pause, searchQuery emits &quot;android&quot;.</li><li>flatMapMerge triggers <strong>both API calls in parallel</strong>: searchUsers(&quot;android&quot;) and searchPosts(&quot;android&quot;)</li><li>As soon as either API responds, results are emitted as SearchResult.Users or SearchResult.Posts.</li><li>The UI collects searchResults and renders both lists.</li></ol><h4>Benefits</h4><ul><li><strong>Parallel execution:</strong> Both APIs are queried at the same time.</li><li><strong>Faster results:</strong> UI can show partial results immediately (e.g., users first, then posts).</li><li><strong>Scalable:</strong> You can merge multiple sources (news, music, shopping, etc.).</li></ul><p>👉 This pattern is great when you want <strong>multi-source search</strong> or <strong>parallel data fetching</strong>.</p><h4><strong>4. flatMapLatest</strong></h4><p>flatMapLatest in Kotlin Flow transforms each emitted value into a new Flow, but whenever a new value arrives, it <strong>cancels the previous inner flow</strong> and switches to the latest one. This makes it ideal for scenarios like search bars, where only the most recent query matters.</p><ul><li><strong>Definition:</strong> Returns a flow that switches to a new inner flow every time the upstream emits.</li><li><strong>Behavior:</strong> If a new value arrives before the previous inner flow finishes, the old flow is canceled immediately.</li><li><strong>Result:</strong> Only emissions from the <em>latest</em> flow are collected.</li></ul><p>A common real-world scenario for flatMapLatest is implementing a search bar that cancels outdated searches whenever the user types a new query. In this setup, we use a SearchRepository class that provides two methods—searchUsers() and searchPosts()—to fetch data from their respective APIs.</p><h4>SearchViewModel</h4><pre>class SearchViewModel(private val repository: SearchRepository) : ViewModel() {<br><br>    // Flow that collects search queries from UI<br>    private val _searchQuery = MutableStateFlow(&quot;&quot;)<br>    val searchQuery: StateFlow&lt;String&gt; = _searchQuery<br><br>    // Expose search results as Flow<br>    val searchResults: Flow&lt;List&lt;Result&gt;&gt; = searchQuery<br>        .debounce(300) // wait for typing to pause<br>        .filter { query -&gt; query.isNotBlank() } // ignore empty queries<br>        .flatMapLatest { query -&gt;<br>            repository.searchUsers(query) // cancels old search if new query arrives<br>        }<br>        .flowOn(Dispatchers.IO) // run on background thread<br><br>    fun updateQuery(query: String) {<br>        _searchQuery.value = query<br>    }<br>}</pre><p>flatMapLatest { query -&gt; repository.searchUsers(query) }</p><ul><li>For each query, it calls repository.searchUsers(query) which returns a Flow&lt;List&lt;Result&gt;&gt;.</li><li>flatMapLatest<strong>behavior: </strong>If a new query arrives before the previous search finishes, the old search flow is <strong>canceled immediately</strong>.</li><li>Only the latest query’s results are collected.</li><li>This is perfect for search bars: you don’t want outdated results if the user keeps typing.</li></ul><h4>Execution Flow Example</h4><p>Imagine the user types quickly: &quot;a&quot; → &quot;an&quot; → &quot;and&quot; → &quot;android&quot;</p><ul><li>&quot;a&quot; triggers a search, but before it completes, &quot;an&quot; arrives → cancel &quot;a&quot;.</li><li>&quot;an&quot; triggers a search, but &quot;and&quot; arrives → cancel &quot;an&quot;.</li><li>&quot;and&quot; triggers a search, but &quot;android&quot; arrives → cancel &quot;and&quot;.</li><li>Only the <strong>latest query </strong>&quot;android&quot; completes and emits results.</li></ul><h4>Benefits</h4><ul><li><strong>Efficient:</strong> Cancels outdated searches automatically.</li><li><strong>Responsive:</strong> UI always shows the latest results.</li><li><strong>Clean:</strong> Structured concurrency ensures no leaks or dangling jobs.</li></ul><h4><strong>Comparison Table</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*x5Yk0iWwey10f03rot2xWA.png" /></figure><h4>Real-World Android Examples</h4><ul><li><strong>Search Bar:</strong> Use <strong>flatMapLatest </strong>to cancel old queries when the user types a new one.</li><li><strong>Multi-source Fetch:</strong> Use <strong>flatMapMerge </strong>to query multiple APIs in parallel (e.g., books + movies).</li><li><strong>Chained Operations:</strong> Use <strong>flatMapConcat </strong>when tasks must run sequentially (e.g., login → fetch profile → fetch settings).</li></ul><h4>📝 Conclusion</h4><p>Choosing the right flattening operator is about <strong>intent</strong>:</p><ul><li>Use <strong>flatMapConcat </strong>for ordered, sequential tasks.</li><li>Use <strong>flatMapMerge </strong>for parallel, independent tasks.</li><li>Use <strong>flatMapLatest </strong>for real-time scenarios where only the latest result matters.</li></ul><p>Mastering these operators makes your Kotlin Flow code <strong>cleaner, faster, and more predictable</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99eaa041f10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Multi-View Types in RecyclerView: one RecyclerView, many row types]]></title>
            <link>https://medium.com/@vaghela.mithun/designing-multi-view-types-in-recyclerview-one-recyclerview-many-row-types-8a793e67760c?source=rss-55465e48cfa8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a793e67760c</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Vaghela Mithun]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 14:13:07 GMT</pubDate>
            <atom:updated>2025-12-02T14:13:07.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Designing Multi-View Types in RecyclerView: one RecyclerView, many row types" src="https://cdn-images-1.medium.com/max/1024/1*LHgpI7qgl7ehWwLy83sN0A.jpeg" /></figure><p>RecyclerView is a cornerstone of modern Android development because it combines <strong>performance, flexibility, and scalability</strong>. Whether you’re building a simple to-do list or a complex social media feed, RecyclerView ensures smooth user experiences and efficient resource management.</p><p>But RecyclerView isn’t just about displaying lists — it’s powerful enough to handle <strong>multiple view types</strong> within a single list. This is especially useful when your app needs to show different kinds of content in one feed, like text posts, images, ads, or videos.</p><h4>Why Multi-View Types Matter</h4><ul><li>Social media feeds often mix posts, stories, and sponsored ads.</li><li>E-commerce apps display product cards, banners, and recommendations.</li><li>News apps combine headlines, images, and video snippets.</li></ul><p>Instead of creating separate RecyclerViews for each type, you can design one <strong>RecyclerView with multiple view types</strong>.</p><h3>Approaches to Implement Multi-View Types</h3><h4>1. Using Interfaces</h4><ul><li>Define an interface (e.g., ListItemInterface) with a method like getItemType().</li></ul><pre>interface ListItemInterface {<br>    fun getItemType(): Int<br>}</pre><ul><li>Each data model implements the ListItemInterface and defines its own type. This allows the adapter to distinguish between different item layouts at runtime.</li><li>For example, consider the Group and ListSection entities. Both implement the ListItemInterface, but each returns a unique type identifier. This makes it possible to handle multiple view types within a single RecyclerView seamlessly.</li></ul><pre>@Parcelize<br>@Entity(tableName = &quot;group&quot;)<br>data class Group(<br>    @PrimaryKey(autoGenerate = true)<br>    val groupId: Int,<br>    val groupName: String<br>) : Parcelable, ListItemInterface {<br>    override fun getItemType(): Int = ITEM_GROUP_TYPE<br>}</pre><pre>data class ListSection(<br>    val section: String<br>) : ListItemInterface {<br>    override fun getItemType(): Int = ITEM_SECTION_TYPE<br>}</pre><ul><li>Generate a data list type of ListItemInterface</li></ul><pre>fun buildInterfaceSampleList(): LinkedList&lt;ListItemInterface&gt; {<br>        return LinkedList&lt;ListItemInterface&gt;().apply {<br>            ....<br>            ....<br>            add(ListSection(&quot;Groups&quot;))<br>            add(Group(groupId = GroupType.SUPER_FOURS.id, groupName = GroupType.SUPER_FOURS.value))<br>            ....<br>        }<br>    }</pre><ul><li>The adapter uses this type to decide which layout to inflate.</li></ul><pre>override fun getItemViewType(position: Int): Int {<br>    return getItem(position).getItemType()<br>}<br><br>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>   if (viewType == ITEM_GROUP_TYPE) {<br>       val binding = ListItemRowGroupBinding.inflate(inflater, parent, false)<br>       return GroupViewHolder(binding)<br>   } else return super.onCreateViewHolder(parent, viewType)<br>}</pre><p>You can check full source code of interface example to achieve multi-type RecyclerView.</p><p><a href="https://github.com/riontech-xten/multy-viewtype-recyclerview/tree/master/interfacesample">multy-viewtype-recyclerview/interfacesample at master · riontech-xten/multy-viewtype-recyclerview</a></p><h4>2. Using Sealed Classes (Kotlin)</h4><ul><li>Create a sealed class hierarchy (e.g., ListItem) with subclasses like Section, Match, Group, Team, AdBanner.</li></ul><pre>sealed class ListItem(open val data: Any?) {<br><br>    /** A header/section item. Implements [ListItem] so adapters that rely on<br>     * that interface can detect headers easily. */<br>    data class Section&lt;T&gt;(override val data: T) : ListItem(data)<br><br>    /** A match item (e.g. a match result). */<br>    data class Match&lt;T&gt;(override val data: T) : ListItem(data)<br><br>    /** A team item (e.g. team points row). */<br>    data class Team&lt;T&gt;(override val data: T) : ListItem(data)<br><br>    /** A group item (e.g. group header or descriptor). */<br>    data class Group&lt;T&gt;(override val data: T) : ListItem(data)<br><br>    /** An ad/banner item for promotional content. */<br>    data class AdBanner&lt;T&gt;(override val data: T) : ListItem(data)<br>}</pre><ul><li>The adapter checks the subclass type and binds the correct view.</li></ul><pre>override fun getItemViewType(position: Int): Int {<br>    val item = getItem(position)<br>    return if (item is ListItem.Match&lt;*&gt;) ITEM_MATCH_TYPE<br>    else if (item is ListItem.Group&lt;*&gt;) ITEM_GROUP_TYPE<br>    else if (item is ListItem.Team&lt;*&gt;) ITEM_TEAM_TYPE<br>    else if (item is ListItem.AdBanner&lt;*&gt;) ITEM_AD_BANNER_TYPE<br>    else ITEM_SECTION_TYPE<br>}<br><br>override fun onCreateViewHolder(<br>    parent: ViewGroup,<br>    viewType: Int<br>): RecyclerView.ViewHolder {<br>    return when (viewType) {<br>        ITEM_MATCH_TYPE -&gt; {<br>            val binding = ListItemRowMatchBinding.inflate(inflater, parent, false)<br>            MatchViewHolder(binding)<br>        }<br><br>        ITEM_GROUP_TYPE -&gt; {<br>            val binding = ListItemRowGroupBinding.inflate(inflater, parent, false)<br>            GroupViewHolder(binding)<br>        }<br><br>        ITEM_TEAM_TYPE -&gt; {<br>            val binding = ListItemRowTeamBinding.inflate(inflater, parent, false)<br>            TeamViewHolder(binding)<br>        }<br><br>        ITEM_AD_BANNER_TYPE -&gt; {<br>             val binding = ListItemAdBannerBinding.inflate(inflater, parent, false)<br>             AdBannerViewHolder(binding)<br>        }<br><br>        ITEM_SECTION_TYPE -&gt; {<br>             val binding = ListItemRowSectionBinding.inflate(inflater, parent, false)<br>             SectionViewHolder(binding)<br>        }<br><br>        else -&gt; {<br>             throw IllegalArgumentException(&quot;Invalid view type&quot;)<br>        }<br>    }<br>}</pre><ul><li>This approach is cleaner and leverages Kotlin’s type safety.</li></ul><pre>fun buildSealedClassSampleList(): LinkedList&lt;ListItem&gt; {<br>     return LinkedList&lt;ListItem&gt;().apply {<br>        .... <br>        add(ListItem.Section(&quot;Groups&quot;))<br>        add(<br>            ListItem.Group(<br>               Group(<br>                     groupId = GroupType.SUPER_FOURS.id,<br>                     groupName = GroupType.SUPER_FOURS.value<br>                    )<br>            )<br>        )<br>            ....<br>      }<br> }</pre><p>You can check the complete code of sealed class example</p><p><a href="https://github.com/riontech-xten/multy-viewtype-recyclerview/tree/master/sealedclasssample">multy-viewtype-recyclerview/sealedclasssample at master · riontech-xten/multy-viewtype-recyclerview</a></p><blockquote>If you check the GitHub repository above, you’ll find another example called <strong>MultiTypeAdapter</strong>. This example demonstrates how to implement the <strong>single adapter design pattern</strong> to handle multiple view types within a single RecyclerView.</blockquote><p>This is a classic design decision in Android development when dealing with <strong>multi-view types in a RecyclerView</strong>. Let’s break it down clearly</p><h3>1. Single Adapter with Multiple View Types</h3><p><strong>How it works</strong>:</p><ul><li>One adapter handles all item types. You override getItemViewType() to return a type identifier, then inflate different layouts in onCreateViewHolder() and bind accordingly in onBindViewHolder().</li></ul><p><strong>Pros</strong>:</p><ul><li>Centralized logic → easier to manage if the list is small or moderately complex.</li><li>Less boilerplate → only one adapter class.</li><li>Easier to handle shared behaviors (e.g., click listeners, diffing).</li></ul><p><strong>Cons</strong>:</p><ul><li>Can get <strong>bloated</strong> quickly if you have many view types.</li><li>Harder to maintain → lots of when/switch statements.</li><li>Testing individual view types is less isolated.</li></ul><h3>2. Adapter Hierarchy (Different Adapters per View Type)</h3><p><strong>How it works</strong>:</p><ul><li>You create separate adapter classes (or delegate classes) for each view type. A parent adapter delegates binding to the correct child adapter.</li></ul><p><strong>Pros</strong>:</p><ul><li><strong>Separation of concerns</strong> → each view type has its own adapter logic.</li><li>Easier to maintain and test → changes in one view type don’t affect others.</li><li>Scales better for complex UIs (e.g., dashboards, feeds with many item types).</li></ul><p><strong>Cons</strong>:</p><ul><li>More boilerplate → multiple adapter classes.</li><li>Slightly more complex setup (delegation, composition).</li><li>Can be overkill for simple lists.</li></ul><h3>Which Approach is Best?</h3><p><strong>Use a single adapter</strong> if:</p><ul><li>You have only a few view types (2–3).</li><li>The binding logic is simple.</li><li>You want quick implementation with minimal boilerplate.</li></ul><p><strong>Use adapter hierarchy / delegate pattern</strong> if:</p><ul><li>You have many view types (4+).</li><li>Each view type has complex binding logic.</li><li>You want clean separation, scalability, and testability.</li><li>You’re building something like a <strong>news feed, e-commerce catalog, or dashboard</strong> where new item types may be added in the future.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a793e67760c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>