<?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 Balvinder Gambhir on Medium]]></title>
        <description><![CDATA[Stories by Balvinder Gambhir on Medium]]></description>
        <link>https://medium.com/@balvinder.gambhir?source=rss-509cf1ac9e4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uJMGqTLk-PdMwR8dD3k54A@2x.jpeg</url>
            <title>Stories by Balvinder Gambhir on Medium</title>
            <link>https://medium.com/@balvinder.gambhir?source=rss-509cf1ac9e4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 23:39:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balvinder.gambhir/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[Building a Pokémon Explorer on Android with AG-UI]]></title>
            <link>https://medium.com/@balvinder.gambhir/building-a-pok%C3%A9mon-explorer-on-android-with-ag-ui-bdbf41258fc5?source=rss-509cf1ac9e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdbf41258fc5</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ag-ui]]></category>
            <dc:creator><![CDATA[Balvinder Gambhir]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 18:12:31 GMT</pubDate>
            <atom:updated>2026-08-02T14:02:53.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3yEHVnP2ZLarkTThxgbdg.png" /><figcaption>Psyduck playing with pokemon explorer</figcaption></figure><p>In the age of LLMs, being asked to build a chatbot has become a basic product requirement. The more interesting challenge is how the client and agent coordinate once the conversation involves tools, application state, progress updates, and errors.</p><p>Today, I will show you how to use AG-UI as the event-based interaction protocol between an Android client and an AI agent. AG-UI gives both sides a shared vocabulary for messages, tool calls, state changes, lifecycle updates, and errors.</p><p>We will explore this through a Pokémon Explorer for Android. The app can look up a Pokémon, search by type, compare two Pokémon, and manage favorites. Each request can update the conversation, show the agent’s current activity, and render structured results with Jetpack Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*8IzLAKhczPvFSU8LP1aURg.jpeg" /></figure><p>The app does not parse this data from the assistant’s response. Text, tool activity, structured Pokémon data, lifecycle updates, and errors all arrive through the same AG-UI event stream.</p><p>In this article, we will connect:</p><ul><li>a Google ADK agent backed by PokeAPI</li><li>a FastAPI endpoint exposed through AG-UI</li><li>the AG-UI Kotlin client</li><li>a Compose UI that renders structured agent state</li></ul><p>The complete demo is available in the <a href="https://github.com/balvinderz/Pokemon-explorer/">AG-UI Pokémon Explorer repository</a>.<br>A live web demo is also available at <a href="https://pokemon-explorer.balvindersi2.workers.dev/">https://pokemon-explorer.balvindersi2.workers.dev/</a></p><h3>Why the Android Client Needs More Than Text</h3><p>A traditional chat API gives the UI a generated response. That works until the agent begins using tools and changing application state.</p><p>When the user asks for three fire-type Pokémon, the client needs to distinguish between the active tool call, the structured search result, and the agent’s final explanation. Treating all three as text would force the app to parse model output and couple its UI to the wording of each response.</p><p>AG-UI provides these as separate events, allowing Android to handle each one directly.</p><h3>What Is AG-UI?</h3><p><a href="https://docs.ag-ui.com/">AG-UI</a> is an open, event-based protocol for communication between agent backends and user-facing applications.</p><p>AG-UI does not define how an agent reasons. Google ADK is responsible for running the agent in this demo. AG-UI defines how Android starts a run and how messages, tool calls, state changes, lifecycle events, and errors travel between the client and backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gI7RhMUqmJu0OVQ2.png" /></figure><p>The client receives a stream of events such as:</p><pre>RUN_STARTED<br>TOOL_CALL_START<br>TOOL_CALL_ARGS<br>TOOL_CALL_RESULT<br>STATE_DELTA<br>TEXT_MESSAGE_CONTENT<br>RUN_FINISHED<br>RUN_ERROR</pre><p>That gives the UI a stable contract without tying it to a particular model or agent implementation.</p><h3>The Android Experience</h3><p>The demo supports one continuous conversation:</p><pre>Show me Pikachu.<br>Show me three fire-type Pokémon.<br>Compare Pikachu and Raichu.<br>Mark Pikachu and Charizard as favorites.<br>Show my favorite Pokémon.<br>Remove Pikachu from my favorites.</pre><p>Each turn can produce both an assistant message and a structured Compose result: a detail card, search grid, comparison, or favorites grid.</p><p>The welcome screen provides prompts instead of leaving the user with an empty chat box. While a run is active, the input is disabled and the app displays the current activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSr_PNIHIOfIURPCq39w1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fc3No8TRtUPoMc3_FkzOWg.png" /></figure><h3>Building the Five-Tool Agent</h3><p>The backend uses Google ADK, the AG-UI ADK middleware, FastAPI, and <a href="https://pokeapi.co/docs/v2">PokeAPI v2</a>.</p><p>The agent exposes five focused tools:</p><p>ToolPurposeget_pokemonRetrieve one Pokémon with artwork, abilities, and statsfind_pokemon_by_typeFind Pokémon belonging to a requested typecompare_pokemonRetrieve exactly two Pokémon for comparisonset_favoritesAdd or remove one or more favoriteslist_favoritesReturn the current favorites</p><p>Each data tool normalizes the PokeAPI response into the same UI-friendly shape. For example:</p><pre>{<br>  &quot;id&quot;: 25,<br>  &quot;name&quot;: &quot;Pikachu&quot;,<br>  &quot;apiName&quot;: &quot;pikachu&quot;,<br>  &quot;heightMeters&quot;: 0.4,<br>  &quot;weightKg&quot;: 6.0,<br>  &quot;types&quot;: [&quot;electric&quot;],<br>  &quot;abilities&quot;: [&quot;static&quot;, &quot;lightning-rod&quot;],<br>  &quot;stats&quot;: [<br>    {&quot;name&quot;: &quot;hp&quot;, &quot;value&quot;: 35},<br>    {&quot;name&quot;: &quot;speed&quot;, &quot;value&quot;: 90}<br>  ],<br>  &quot;imageUrl&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/25.png&quot;<br>}</pre><p>The important part is what happens after a tool succeeds:</p><pre>tool_context.state[&quot;selected_pokemon&quot;] = pokemon<br>tool_context.state[&quot;search_results&quot;] = pokemon<br>tool_context.state[&quot;pokemon_comparison&quot;] = pokemon<br>tool_context.state[&quot;favorites&quot;] = favorites</pre><p>Those assignments become structured state updates in the AG-UI stream. Compose can render the data without extracting facts from the assistant’s response.</p><p>The tools are registered directly with LlmAgent:</p><pre>agent = LlmAgent(<br>    name=&quot;pokemon_explorer_agent&quot;,<br>    model=MODEL_NAME,<br>    instruction=&quot;...&quot;,<br>    tools=[<br>        get_pokemon,<br>        find_pokemon_by_type,<br>        compare_pokemon,<br>        set_favorites,<br>        list_favorites,<br>    ],<br>)</pre><p>The instruction requires the agent to use the appropriate tool and return concise plain text. Compose owns the rich presentation.</p><p>The complete implementation, including PokeAPI caching and error handling, is in <a href="https://github.com/balvinderz/Pokemon-explorer/blob/main/agent/server.py">agent/server.py</a>.</p><h3>Exposing the Agent through AG-UI</h3><p>The ag_ui_adk integration package provides the adapter and FastAPI endpoint helper:</p><pre>from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint</pre><pre>ag_ui_agent = ADKAgent(<br>    adk_agent=agent,<br>    app_name=&quot;kotlin_agui_pokemon_demo&quot;,<br>    user_id=&quot;android-pokemon-user&quot;,<br>    session_timeout_seconds=3600,<br>    use_in_memory_services=True,<br>    use_thread_id_as_session_id=True,<br>)</pre><pre>app = FastAPI(title=&quot;Kotlin AG-UI Pokemon Explorer Demo&quot;)<br>add_adk_fastapi_endpoint(app, ag_ui_agent, path=&quot;/agent&quot;)</pre><p>use_thread_id_as_session_id=True maps an AG-UI thread to an ADK session. A favorite added in one message therefore remains available to later messages sent on the same thread.</p><h3>Connecting Android</h3><p>The Android module adds the AG-UI Kotlin client:</p><pre>implementation(&quot;com.ag-ui.community:kotlin-client:0.4.1&quot;)</pre><p>The emulator connects to the host server through:</p><pre>http://10.0.2.2:8002/agent</pre><p>The ViewModel owns one StatefulAgUiAgent, a stable thread ID, and a StateManager:</p><pre>private const val THREAD_ID = &quot;pokemon-explorer&quot;</pre><pre>private val agent = StatefulAgUiAgent(AGENT_URL) {<br>    systemPrompt = &quot;Help the user discover Pokemon and manage favorites.&quot;<br>    requestTimeout = 120_000L<br>    connectTimeout = 15_000L<br>}</pre><pre>private val stateManager = StateManager(<br>    initialState = JsonObject(emptyMap()),<br>)</pre><p>Calling chat() returns a Flow&lt;BaseEvent&gt;. Every event first goes through StateManager, then the ViewModel translates it into screen state.</p><h3>Understanding Agent State</h3><p>Before mapping events to Compose, it helps to separate the agent’s state from the chat messages.</p><p>The backend tools write four fields to the ADK session:</p><pre>{<br>  &quot;selected_pokemon&quot;: {},<br>  &quot;search_results&quot;: [],<br>  &quot;pokemon_comparison&quot;: [],<br>  &quot;favorites&quot;: []<br>}</pre><p>When one of these fields changes, AG-UI sends the change as a state event. The Kotlin StateManager processes that event and merges it into its current JSON state:</p><pre>eventStream.collect { event -&gt;<br>    stateManager.processEvent(event)</pre><pre>val currentState = stateManager.currentState.value<br>}</pre><p>The app then converts the JSON into a typed model:</p><pre>data class PokemonAgentState(<br>    val selectedPokemon: PokemonSummary? = null,<br>    val searchResults: List&lt;PokemonSummary&gt; = emptyList(),<br>    val comparison: List&lt;PokemonSummary&gt; = emptyList(),<br>    val favorites: List&lt;PokemonSummary&gt; = emptyList(),<br>)</pre><pre>val pokemonState = stateManager.currentState.value<br>    .toPokemonAgentStateOrEmpty()</pre><p>StateManager owns the latest protocol state, while PokemonAgentState gives the Android code a type-safe representation that Compose can consume. Neither one contains loading indicators, errors, or other UI-only state.</p><p>The JSON-to-model conversion is in <a href="https://github.com/balvinderz/Pokemon-explorer/android-app/app/src/main/java/com/example/aguipokemon/PokemonModels.kt">PokemonModels.kt</a>.</p><h3>Combining Agent State with Screen State</h3><p>The screen also needs conversation and presentation state. The ViewModel combines these concerns in PokemonScreenState:</p><pre>data class PokemonScreenState(<br>    val messages: List&lt;ChatMessage&gt; = emptyList(),<br>    val pokemon: PokemonAgentState = PokemonAgentState(),<br>    val turnResults: Map&lt;String, PokemonTurnResult&gt; = emptyMap(),<br>    val isRunning: Boolean = false,<br>    val activeTool: String? = null,<br>    val error: String? = null,<br>)</pre><p>The distinction is:</p><ul><li>pokemon comes from AG-UI state events.</li><li>messages comes from the agent&#39;s thread history.</li><li>isRunning, activeTool, and error describe the current UI state.</li><li>turnResults preserves the structured result associated with each message.</li></ul><p>With those responsibilities separated, the event mapping becomes easier to follow:</p><p>AG-UI signalViewModel updateVisible resultTOOL_CALL_STARTSet activeTool“Comparing Pokémon…”STATE_DELTAUpdate StateManagerTyped Pokémon and favorite stateText message eventsRead agent historyAssistant chat bubbleRUN_FINISHEDSave the result by message IDStable result cardRUN_ERRORSet errorError message</p><p>An abridged version of the collection loop shows the event handling:</p><pre>eventStream.collect { event -&gt;<br>    stateManager.processEvent(event)<br>    when (event) {<br>            is ToolCallStartEvent -&gt; {<br>                toolsUsed += event.toolCallName<br>                activeTool = event.toolCallName.toActivityLabel()<br>            }<br>            is TextMessageStartEvent -&gt; {<br>                responseMessageId = event.messageId<br>            }<br>            is RunFinishedEvent -&gt; {<br>                activeTool = null<br>            }<br>            else -&gt; Unit<br>        }<br>    updateScreenState(event)<br>}</pre><p>The repository contains the complete collection and error-handling logic in <a href="https://github.com/balvinderz/Pokemon-explorer/android-app/app/src/main/java/com/example/aguipokemon/PokemonAgentViewModel.kt">PokemonAgentViewModel.kt</a>.</p><h3>Preserving Results beside Their Messages</h3><p>The agent state always represents the latest known state. That creates a subtle chat-history problem.</p><p>If the user asks for Pikachu and then Charizard, every old message must not render the latest selected_pokemon. Otherwise the earlier Pikachu card would turn into Charizard.</p><p>The demo snapshots the part of state produced by each completed run:</p><pre>data class PokemonTurnResult(<br>    val selectedPokemon: PokemonSummary? = null,<br>    val searchResults: List&lt;PokemonSummary&gt;? = null,<br>    val comparison: List&lt;PokemonSummary&gt;? = null,<br>    val favorites: List&lt;PokemonSummary&gt;? = null,<br>)</pre><p>At RUN_FINISHED, the ViewModel filters the state using toolsUsed and stores the result under the assistant message ID. In condensed form:</p><pre>if (event is RunFinishedEvent &amp;&amp; responseMessageId != null) {<br>    pokemonState.toTurnResult(toolsUsed)?.let { result -&gt;<br>        turnResults += responseMessageId!! to result<br>    }<br>}</pre><p>This gives the app two distinct concepts:</p><ul><li>PokemonAgentState is the live session state.</li><li>PokemonTurnResult is the stable result of one conversation turn.</li></ul><p>AG-UI synchronizes the live state. The ViewModel adds the small amount of presentation state required to preserve the conversation.</p><h3>Rendering Native Results</h3><p>The Compose list looks up the result belonging to each assistant message:</p><pre>AssistantMessage(<br>    text = message.text,<br>    result = screenState.turnResults[message.id],<br>    favoriteNames = favoriteNames,<br>    onPokemonClick = onPokemonClick,<br>    onFavoriteChange = onFavoriteChange,<br>)</pre><p>PokemonTurnResultContent selects a PokemonDetail, PokemonGrid, or PokemonComparison based on the result. The assistant supplies the explanation while Compose owns images, stat bars, type badges, layout, and actions.</p><p>The full UI is in <a href="https://github.com/balvinderz/Pokemon-explorer/android-app/app/src/main/java/com/example/aguipokemon/PokemonScreen.kt">PokemonScreen.kt</a>.</p><h3>Closing the Interaction Loop</h3><p>The cards are interactive. Tapping a Pokémon requests its details, and tapping a heart asks the agent to update the favorites:</p><pre>fun showPokemon(name: String) =<br>    send(&quot;Tell me about $name.&quot;)</pre><pre>fun setFavorite(name: String, favorite: Boolean) {<br>    val prompt = if (favorite) {<br>        &quot;Mark $name as a favorite.&quot;<br>    } else {<br>        &quot;Remove $name from my favorites.&quot;<br>    }<br>    send(prompt)<br>}</pre><p>The UI does not directly mutate the agent’s session state. It requests the change and responds to the resulting state event, keeping one source of truth.</p><h3>Runs, Threads, and Session State</h3><p>An AG-UI run represents one request. A thread represents the conversation:</p><pre>Conversation: lookup ------ compare -------- add favorite<br>Run:          [open-close]  [open----close]  [open-----close]<br>Thread:       [------------------------------------------]</pre><p>The Android app reuses:</p><pre>private const val THREAD_ID = &quot;pokemon-explorer&quot;</pre><p>Because the backend maps that thread to an ADK session, every run resumes the same favorites state. Creating a new thread for every message would create a new session and make favorites appear to disappear.</p><h3>Running the Pokemon Demo</h3><p>From the repository root, install and start the agent:</p><pre>python3 -m pip install -r agent/requirements.txt<br>export GOOGLE_API_KEY=&quot;your-google-api-key&quot;<br>python3 agent/server.py --host 0.0.0.0 --port 8002</pre><p>Verify it:</p><pre>curl http://127.0.0.1:8002/health</pre><p>Then open android-app in Android Studio and run the app configuration, or build from the command line:</p><pre>cd android-app<br>./gradlew :app:assembleDebug</pre><p>For a physical device, reverse the agent port:</p><pre>adb reverse tcp:8002 tcp:8002</pre><p>and change AGENT_URL to:</p><pre>http://127.0.0.1:8002/agent</pre><p>The repository <a href="https://github.com/balvinderz/Pokemon-explorer/blob/main/README.md">README</a> contains the complete Android setup.</p><h3>The Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8W0OJv5KhRVkQs_PQXUqw.gif" /></figure><p>AG-UI lets the Android app observe an agent run as structured events instead of treating it as one text response.</p><p>In this demo, one event stream powers streamed messages, tool-specific activity, detail cards, type-search grids, comparisons, persistent favorites, interactive actions, and errors.</p><p>The agent decides which tools to use and owns session state. Compose owns presentation and Android interaction. AG-UI is the event contract that keeps them synchronized.</p><p>That separation is what turns a chat integration into an agent-native Android experience.</p><h3>Resources</h3><ul><li><a href="https://docs.ag-ui.com/concepts/events">AG-UI events</a></li><li><a href="https://google.github.io/adk-docs/">Google Agent Development Kit</a></li><li><a href="https://pokeapi.co/docs/v2">PokeAPI v2</a></li><li><a href="https://github.com/balvinderz/Pokemon-explorer/blob/main/README.md">Demo code</a></li></ul><p>In the next article, we will move from agent-driven data to agent-driven UI. Using A2UI with AG-UI, the agent will generate a declarative UI description at runtime and the Android app will render it with native Compose components. This allows the interface to adapt to each request while the client remains in control of what can be rendered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdbf41258fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Swiggy Migrated from protobuf-java to Square Wire]]></title>
            <link>https://medium.com/swiggy-bytes/how-swiggy-migrated-from-protobuf-java-to-square-wire-e97d435c86d3?source=rss-509cf1ac9e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97d435c86d3</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[square-wire]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Balvinder Gambhir]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 05:14:33 GMT</pubDate>
            <atom:updated>2026-07-10T05:17:10.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYQRNWaafakkF6uEP7CJAA.png" /></figure><p>At Swiggy, we use Protocol Buffers everywhere. Nearly every message exchanged between our backend services and our mobile apps is a protobuf. On Android, the default and most widely adopted way to work with those schemas was protobuf-java, Google’s official Java runtime, with Java classes generated by protoc.</p><p>It worked. But when we started profiling our app size, we found that protobuf-java and the code generated by protoc collectively were consuming <strong>6.735 MB</strong> of our overall app size. That is a significant chunk, and it became the reason we started planning a migration away from protobuf-java.</p><p>App size is not just a vanity metric for us. Every additional MB affects install conversion, update reliability, and the size budgets of multiple Android apps built on the same platform stack. Since protobuf sits in a shared layer, any improvement here would not be limited to one screen or one feature. It had the potential to reduce size across <strong>Swiggy</strong>, <strong>Instamart</strong>, and <strong>Toing</strong>.</p><h3>Why Not Just Switch to protobuf-javalite?</h3><p>The obvious answer to a bloated protobuf runtime is protobuf-javalite — Google&#39;s trimmed-down version built specifically for Android. Smaller runtime, less generated code, same wire format.</p><p>We could not use it. The Swiggy app uses google.protobuf.Any extensively across its schema — it is how our APIs handle dynamic, polymorphic payloads. protobuf-javalite strips well-known types, including Any, entirely from the runtime. Switching to lite would have required rearchitecting a significant portion of our serialization layer.</p><p>We needed a library that was smaller than protobuf-java on Android but still supported everything protobuf-java supports, including Any. That led us to Square Wire.</p><h3>What Is Square Wire?</h3><p><a href="https://square.github.io/wire/">Wire</a> is an open-source protobuf implementation maintained by Square. It is byte-for-byte wire-format compatible with protobuf-java — same .proto schemas, same encoding. What changes is the code generator and the runtime library.</p><p>Instead of Java Builder-pattern classes, Wire generates lean, immutable Kotlin objects. The runtime is significantly smaller than protobuf-java. And unlike protobuf-javalite, it supports google.protobuf.Any and the rest of the well-known types.</p><p>Wire also supports JSON serialization out of the box, which is a useful addition — though worth noting that Wire’s JSON parsing speed is significantly slower than its binary parsing. It works, but if you have a high-throughput JSON path, benchmark it before relying on it.</p><h3>The Generated Code: Before and After</h3><p>Take this simple proto:</p><pre>syntax = &quot;proto3&quot;;<br>message CartItem {<br>    string item_id = 1;<br>    string name = 2;<br>    int32 quantity = 3;<br>}</pre><p><strong>What protobuf-java generates (Java):</strong></p><pre>public final class CartItem extends com.google.protobuf.GeneratedMessageV3 {<br>private String itemId_ = &quot;&quot;;<br>private String name_ = &quot;&quot;;<br>private int quantity_ = 0;<br>public String getItemId() { return itemId_; }<br>public String getName()   { return name_; }<br>public int getQuantity()  { return quantity_; }<br>public static Builder newBuilder() { ... }<br>public static final class Builder extends GeneratedMessageV3.Builder&lt;Builder&gt; {<br>    public Builder setItemId(String value) { ... return this; }<br>    public Builder setName(String value)   { ... return this; }<br>    public Builder setQuantity(int value)  { ... return this; }<br>    public CartItem build() { ... }<br>    }<br>}</pre><pre>// To create, modify, encode, and decode:<br>CartItem item = CartItem.newBuilder()<br>    .setItemId(&quot;item_001&quot;)<br>    .setName(&quot;Masala Dosa&quot;)<br>    .setQuantity(2)<br>    .build();</pre><pre>// Modify (must go through builder again)<br>CartItem updated = item.toBuilder()<br>    .setQuantity(3)<br>    .build();</pre><pre>// Encode<br>byte[] bytes = item.toByteArray();</pre><pre>// Decode<br>CartItem item = CartItem.parseFrom(bytes);</pre><p><strong>What Wire generates (Kotlin):</strong></p><pre>class CartItem(<br>    @field:WireField(tag = 1, adapter = &quot;com.squareup.wire.ProtoAdapter#STRING&quot;)<br>    val item_id: String = &quot;&quot;,<br><br>    @field:WireField(tag = 2, adapter = &quot;com.squareup.wire.ProtoAdapter#STRING&quot;)<br>    val name: String = &quot;&quot;,<br><br>    @field:WireField(tag = 3, adapter = &quot;com.squareup.wire.ProtoAdapter#INT32&quot;)<br>    val quantity: Int = 0,<br><br>    unknownFields: ByteString = ByteString.EMPTY<br>) : Message&lt;CartItem, CartItem.Builder&gt;(ADAPTER, unknownFields) {<br><br>    fun copy(<br>        item_id: String = this.item_id,<br>        name: String = this.name,<br>        quantity: Int = this.quantity<br>    ): CartItem = CartItem(item_id, name, quantity)<br><br>    companion object {<br>        @JvmField<br>        val ADAPTER: ProtoAdapter&lt;CartItem&gt; = ...<br>    }<br>}</pre><p>To create, modify, encode, and decode:</p><pre>// Create<br>val item = CartItem(<br>    item_id = &quot;item_001&quot;,<br>    name = &quot;Masala Dosa&quot;,<br>    quantity = 2<br>)</pre><pre>// Modify<br>val updated = item.copy(quantity = 3)</pre><pre>// Encode<br>val bytes: ByteArray = CartItem.ADAPTER.encode(item)</pre><pre>// Decode<br>val item: CartItem = CartItem.ADAPTER.decode(bytes)</pre><p>The difference in generated code is visible immediately. Wire produces a straightforward Kotlin class with public properties. No builder boilerplate, no getter methods, no intermediate allocation for construction or modification.</p><h3>What the Migration Actually Looks Like</h3><h3>Field Names</h3><p>protobuf-java generates camelCase Java getters. A field called user_id in your .proto becomes getUserId() in Java. Wire keeps the original snake_case name as a Kotlin property, so getUserId() becomes user_id.</p><p>Every field access in the codebase needs to be updated. A regex or IDE structural search handles most of it, but budget real time for this — it is the most labour-intensive part of the migration.</p><h3>Building and Copying Messages</h3><p>With protobuf-java, every message is constructed through newBuilder(). Wire generates a plain Kotlin constructor instead, so you pass fields as named arguments directly. Modifying a message is a copy() call rather than a round-trip through a builder. The resulting code is noticeably cleaner.</p><h3>Encoding and Decoding</h3><p>With protobuf-java, messages serialise themselves: message.toByteArray(), MyMessage.parseFrom(bytes). Wire moves this to a static ADAPTER on each generated class: MyMessage.ADAPTER.encode(message), MyMessage.ADAPTER.decode(bytes). Every serialisation call site in the codebase needs updating.</p><h3>The Packed Encoding Gotcha</h3><p>This is the issue to watch out for most carefully, because it produces no compile errors and no runtime exceptions — just a silent wire format mismatch.</p><p>The proto3 spec says that repeated scalar fields — integers, enums, and similar — should be packed by default. protobuf-java follows this automatically. Wire does not enable packed encoding for repeated enum fields unless you explicitly annotate the field in the .proto schema with [packed = true].</p><p>We ran into this when sending requests that had a proto as the request body. The server was rejecting or misreading the payload — the repeated enum fields were being encoded unpacked by Wire on the client, while the server expected packed encoding as per the proto3 spec. No crash, no obvious error, just the server not seeing the data it expected.</p><p>The fix was straightforward: add [packed = true] to the relevant repeated fields in the .proto file. But the issue itself is subtle enough that you will not find it without specifically testing your request payloads end-to-end after the migration.</p><h3>ProGuard Rules</h3><p>Getting ProGuard right with Wire took us several rounds of trial and error. The challenge in our case is that we use both binary protobuf and JSON — Wire’s JSON serialization goes through a different code path than binary, and R8 will aggressively strip things that look unreachable from static analysis but are actually needed at runtime.</p><p>After going back and forth, these are the rules that give us the leanest app size without breaking anything on the Wire side:</p><pre># Wire runtime<br>-keep class com.squareup.wire.** { *; }<br>-keepclassmembers class * extends com.squareup.wire.Message {<br>    public static com.squareup.wire.ProtoAdapter ADAPTER;<br>    @com.squareup.wire.WireField &lt;fields&gt;;<br>    &lt;init&gt;(...);<br>    public *** get*();<br>    public *** is*();<br>}<br>-keepnames class * extends com.squareup.wire.WireEnum<br>-keepclassmembers class * extends com.squareup.wire.WireEnum {<br>    public static com.squareup.wire.ProtoAdapter ADAPTER;<br>    public static ** fromValue(int);<br>    ** INSTANCE;<br>    &lt;init&gt;(...);<br>}<br># EnumJsonFormatter checks simpleName == &quot;Companion&quot; to skip companion objects.<br># Without this, R8 renames the companion and the check breaks, producing corrupt JSON.<br>-if class * extends com.squareup.wire.WireEnum<br>-keepnames class &lt;1&gt;$Companion</pre><p>A few things worth explaining:</p><p><strong>ADAPTER</strong> is accessed reflectively at runtime — not through a direct static reference in your own code, but by Wire internally. If R8 removes or renames it, serialization silently breaks.</p><p><strong>@WireField annotations</strong> are how Wire knows which fields to include when encoding a message and how to map bytes back to fields when decoding. Strip them and your messages come out empty.</p><p><strong>fromValue(int)</strong> is called during enum deserialization to resolve an integer back to the right enum constant. R8 will remove it if you do not keep it, causing a crash at decode time.</p><p><strong>$Companion keepnames</strong> is the one that caught us off guard. Wire&#39;s EnumJsonFormatter checks whether a class&#39;s simpleName is &quot;Companion&quot; to skip it when iterating enum members. R8 renames companion classes when they are not otherwise referenced by name, which causes the formatter to fail and crash. The conditional keep rule targets only companions of WireEnum subclasses, so you are not keeping more than you need.</p><h3>The Code Generation Pipeline</h3><p>At Swiggy, we do not use the standard Wire Gradle plugin directly. Our proto schemas live in a monorepo organised into packages, and we wanted to publish one AAR per package to our internal Maven repository on AWS CodeArtifact.</p><p>To support that, we built a custom generation pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHKD2h-KQgfAdy46MdGMMg.png" /></figure><p>The build script scans all proto packages, normalises the file structure (Wire requires that a file’s filesystem path matches its package declaration), runs the Wire compiler once across the entire schema, maps the generated Kotlin files back to their source packages, builds an AAR per package, and publishes to CodeArtifact.</p><p>Running the Wire compiler once for everything — rather than per package — is important. Wire needs to resolve all cross-package type references at compile time, so isolating packages causes unresolved type errors. A single pass over the full schema avoids this.</p><p>We also run incremental builds: only packages with changed files, and their transitive dependents, are rebuilt on each CI run.</p><h3>The Result</h3><p>Switching from protobuf-java to Wire reduced the size of the Swiggy app by <strong>3.52 MB</strong>. The savings came from replacing the full protobuf-java runtime and the heavier protoc-generated classes with Wire’s leaner runtime and generated Kotlin models.</p><p>The impact was not limited to the Swiggy app. <strong>Instamart</strong> and <strong>Toing</strong> also depend on the same protobuf-generated artifacts, so the migration gave us measurable size reductions across those apps as well. That made this more than a single-app optimization; it became a platform-level cleanup across our Android apps.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fuoz8V%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fuoz8V%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fuoz8V%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="227" frameborder="0" scrolling="no"><a href="https://medium.com/media/b412f7d28717fda1ad260ba2e6ec0ff9/href">https://medium.com/media/b412f7d28717fda1ad260ba2e6ec0ff9/href</a></iframe><p>If you are on protobuf-java and looking to reduce your Android app size without giving up features like google.protobuf.Any, Wire is the right move.</p><h4><strong>Acknowledgements</strong></h4><p>I want to thank <a href="https://medium.com/u/723d70adf627">Sambuddha Dhar</a> <a href="https://medium.com/u/1bf9bdb89775">Raj Gohil</a> <a href="https://medium.com/u/400467f4ffab">Tushar Tayal</a> for your continuous support throughout this migration. This migration wouldn’t have been possible without you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97d435c86d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/how-swiggy-migrated-from-protobuf-java-to-square-wire-e97d435c86d3">How Swiggy Migrated from protobuf-java to Square Wire</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Configuration time for Android apps that use React Native]]></title>
            <link>https://medium.com/swiggy-bytes/optimizing-configuration-time-for-android-apps-that-use-react-native-81bb8c9bffdf?source=rss-509cf1ac9e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81bb8c9bffdf</guid>
            <category><![CDATA[hybrid-apps]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Balvinder Gambhir]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 01:51:38 GMT</pubDate>
            <atom:updated>2024-03-25T01:51:38.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iw63cwRzvWJJVu0jyn3eVQ.jpeg" /></figure><p>Swiggy is a super app that hosts a range of business lines, including Food Delivery, Instamart, Dineout, Minis, Insanely Good, Mall, and more. Each of these business lines operates on its own distinct technology stack, with React Native being among the frameworks utilized.</p><p>There was a sharp increase in the time taken to complete the configuration phase of the build process on adding react native to our app. For configuring the project, it was taking more than <strong>1 minute</strong>. Imagine waiting at least 1 minute every time you want to see your changes 😔</p><p>To debug, let’s first understand how our app is built by the gradle build system.</p><p>The build process of gradle goes through various build phases.</p><p>The build phases of gradle are</p><p>1. Initialization phase — In this phase Gradle tries to identify all the projects involved in the build process.</p><p>2. Configuration phase — During this phase, Gradle executes the build script of each project identified in the previous phase</p><p>3. Execution Phase — This is the last phase. During this phase, Gradle identifies the tasks that need to be executed created in the previous phase, and executes them according to their dependency order. All the build work and activities are done in this phase. For example: compiling the app, generating build etc.</p><p>Now that we know the phases of the gradle build process, let’s debug this.</p><p>To debug, let’s run a gradle scan to see what is taking so much time.<br>To run a gradle scan, you can execute the below command</p><pre>./gradlew dependencies --scan</pre><p>Running this will generate a link to get the details of the tasks that were executed.</p><p>By going to the configuration tab ( you can reach it by clicking on performance from the navigation rail and then pressing on the configuration tab), it was observed that the total configuration time for our app was <strong>1 minute and 26 seconds</strong>, with 1 minute and 7 seconds (<strong>86% of the time</strong>) being spent on executing the native_modules.gradle script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZCzb-W6511VGNGgnPeMbA.png" /><figcaption>Configuration Time Breakup</figcaption></figure><p>If your react native app has a dependency on <strong>react-native-community</strong>, then your app will need to apply the native_modules.gradle script. Applying it 1 time can increase the configuration time by around 30 seconds. This was applied two times (one time in settings.gradle and one time in another module), so the increase in time was doubled for us.</p><p>After going through the code written in native_modules.gradle, it was observed that 2 node commands are being executed by the script.</p><p>1.node -e &quot;try {console.log(require(&#39;@react-native-community/cli&#39;).bin);} catch (e){console.log(require(&#39;react-native/cli&#39;).bin;}” — This command resolves the command line path. This command executes very fast.</p><p>2. node $cliPath config — This command generates a JSON output which the gradle command uses to generate PackageList.java. Sample output for this command can be found here — <a href="https://gist.github.com/balvinderg/5821aa34812508fdb1499d540420c948">gist link</a></p><p>The majority of the configuration time is spent in running the node config command. <br>To reduce the configuration phase time, we decided to modify the native_module’s gradle script and cache the output of the config command as it is same for every project configuration given that the package.json and its dependencies have not changed.</p><p>This is how the existing script works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*lLQ8k_rIYVAfWI9Ap2w3gA.png" /><figcaption>Flow diagram for existing native_modules.gradle</figcaption></figure><p>and this will how the modified native_modules.gradle will work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6AWBgxZIa0dP-TTipTokQ.png" /><figcaption>Flow diagram for modified native_modules.gradle</figcaption></figure><p><strong>Explanation</strong></p><ol><li>We are going to cache the output of the node config command and save the output of it in the node_command_output.json file. We will also save the current package.json in cached_package.json and the current package-lock.json in cached_package-lock.json so that we can compare them later while deciding whether to use cached_output or not.</li><li>We are replacing the output of the node config command by replacing the result of root.absolutePath with “to_be_replaced_with” so that the output remains the same for any developer working on the project. We will replace “to_be_replaced_with” back to the root.absolutePath when we are going to use the cache.</li></ol><p>The modified native_module.gradle script can be downloaded from here — <a href="https://gist.github.com/balvinderg/d7b93e329c84ae81eab7936f9c9b8f54">https://gist.github.com/balvinderg/d7b93e329c84ae81eab7936f9c9b8f54</a></p><p>If you are on the latest version of React Native community , you can use this — <a href="https://gist.github.com/balvinderg/d6fafbb75c06e4388cf51ac3d1bf41a1">https://gist.github.com/balvinderg/d6fafbb75c06e4388cf51ac3d1bf41a1</a></p><p>To make sure that all the devs use the same native_modules.gradle script, you can use patch-package.</p><p>To add patch-package, you can add patch-package as a devDependencies in package.json and a script to run patch-package when node modules are installed.</p><pre>{<br>  &quot;name&quot;: &quot;example&quot;,<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;scripts&quot;: { //Add this in your package.json<br>    &quot;postinstall&quot;: &quot;patch-package&quot; //Add this in your package.json<br>  },<br>  &quot;devDependencies&quot;: { <br>    &quot;patch-package&quot;: &quot;6.4.7&quot; //Add this in your package.json<br>  }<br>}</pre><p>Now run command</p><pre>npx patch-package @react-native-community/cli-platform-android</pre><p>after modifying the native_modules.gradle script.<br>This will ensure all devs are using the same native_modules.gradle script while running the builds.</p><p><strong>Results</strong></p><p>After modifying the native_modules.gradle script, our configuration time decreased from 1m 26s to<strong> 12s</strong> i.e an <strong>86% </strong>decrease in configuration time 🚀🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4DivvF5wOXcpM74LTqmXw.png" /><figcaption>Configuration time breakup (after)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsKKVTq5P51yvNAOWYdIiQ.png" /><figcaption>New execution time for native_modules.gradle</figcaption></figure><p><strong>Savings Per Day</strong></p><p>Average build generation per day in Android team— 55<br>Average Savings per build — 74 seconds<br>Total Savings — 55 * 74 = 4070 seconds ~= <strong>1 hour per day</strong></p><h4>Resources</h4><ol><li><a href="https://www.npmjs.com/package/patch-package">https://www.npmjs.com/package/patch-package</a></li><li><a href="https://proandroiddev.com/understanding-gradle-the-build-lifecycle-5118c1da613f">https://proandroiddev.com/understanding-gradle-the-build-lifecycle-5118c1da613f</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81bb8c9bffdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/optimizing-configuration-time-for-android-apps-that-use-react-native-81bb8c9bffdf">Optimizing Configuration time for Android apps that use React Native</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the WhatToEat Experience on Android]]></title>
            <link>https://medium.com/swiggy-bytes/building-the-whattoeat-experience-on-android-8ecf7d010ca8?source=rss-509cf1ac9e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecf7d010ca8</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[custom-layout]]></category>
            <category><![CDATA[swiggy-mobile]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[swiggy-engineering]]></category>
            <dc:creator><![CDATA[Balvinder Gambhir]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 08:22:25 GMT</pubDate>
            <atom:updated>2023-09-01T08:22:25.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tCeBhNn86N2S-xfvEsPC9g.gif" /></figure><h4>Part 1 — Creating the Bubble’s Layout</h4><p><strong>What to Eat?</strong></p><p>It’s a question I have found myself pondering a lot of times. Well, I don’t have to anymore. Why?</p><p>Introducing Swiggy’s WhatToEat, a feature that enhances the traditional food-ordering journey by adding the crucial element of discovering food through emotions.</p><p><strong>Goal</strong></p><p>The goal of “<strong>WhatToEat</strong>” is to help users overcome decision fatigue while ordering food. The feature aims to simplify the decision-making process by allowing users to indicate their current mood or specific cuisine preferences through bubbles.</p><p>In this multi-part series, I will explain how we used<strong> Jetpack Compose</strong> to create the <strong>WhatToEat</strong> feature.</p><ul><li>In the part 1 of our series, we’ll focus on recreating the eye-catching bubble layout that you see in this feature.</li><li>In the next part of the series, I will explain how we animated each of the bubbles.</li></ul><p><strong>Creating the Bubble’s Layout</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*3S_48krOUrb9x7m_76GOCA.png" /><figcaption>Bubbles layout</figcaption></figure><ol><li>The layout consists of a list of bubbles.</li><li>The bubbles are following a 1–2–1–2–1… and so on pattern.</li><li>Every bubble’s position is randomly moved in both horizontal (X) and vertical (Y) directions.</li></ol><p>Our bubble’s UI is very simple. Its just a image with text underneath it. <br>In compose, this is how we implemented it.</p><pre>@Composable<br>fun Bubble(imageUrl: String,<br>           subtitle: String,<br>           modifier: Modifier = Modifier,<br>           contentDescription: String? = null) {<br>    Column(modifier) {<br>        AsyncImage(model = imageUrl, contentDescription = contentDescription)<br>        Text(text = subtitle)<br>    }<br>}</pre><p>Now let’s focus on creating the 1–2–1 pattern. <br>A naive approach to build this would be to create this layout using column with multiple rows inside it. For eg</p><pre>@Composable<br>fun NaiveLayout(bubbles: List&lt;Bubble&gt;){<br>    Column(modifier = Modifier.fillMaxWidth().padding(top = 86.dp)) {<br>        Row(modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.Center) {<br>           Bubble()<br>        }<br>        Row(modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.SpaceAround) {<br>            Bubble()<br>            Bubble()<br>        }<br>        Row(modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.Center) {<br>            Bubble()<br>        }<br>        Row(modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.SpaceAround) {<br>            Bubble()<br>            Bubble()<br>        } <br>        ... and so on<br>    }<br>}</pre><p><strong>Why is this approach naive?</strong></p><ol><li>This layout will not scale if we decide to add more patterns. We will need to add new layouts for each pattern.</li><li>This layout does not support animating the bubbles individually.</li><li>The columns and rows approach is too restrictive. We are dependent on the arrangment property for the bubble’s position. We cannot place the bubble anywhere.</li><li>Earlier we saw that each bubble was randomly moved in the X and Y direction. We cannot do this in this approach (We can do it by using translationY and padding but i feel like that would just be a hackish way to do this).</li></ol><p>So what will be a better approach to make this?</p><p>The answer is <strong>Custom Layout.</strong></p><p>Custom layout gives us the capability to control each composable’s position on a pixel level and is also very simple to use.</p><p>To create a custom layout, compose has a composable called <strong>Layout.</strong></p><p>Layout composable accepts a list of composable and a measurePolicy(this is a way to measure and position the composables).</p><p>Before going to the layout’s code, let’s create an interface for placing the bubbles.<br>The interface will have 2 methods</p><ol><li>place — This method will return us the x and y coordinates for the bubble at position index.</li><li>getLayoutHeight — This will accept the number of bubbles, the bubble’s height and return us the total height the bubbles will take.</li></ol><pre>interface BubblePlacer{<br><br>    /** This function calculates the x and y poisiton for the bubble at any index.<br>     *  [maxWidth] and [widthOfBubble] is used to help decide the x position of the bubble<br>     *  [density] is used to convert dp to px<br>     *  [heightOfBubble] is used to calculate the y position<br>     *  [topPadding] is the padding from top of the screen<br>     */<br>    fun place(<br>        index: Int,<br>        maxWidth: Int,<br>        heightOfBubble: Int,<br>        widthOfBubble: Int,<br>        topPadding: Int,<br>        density: Float<br>    ): IntOffset // this has getters for getting the x and y position.<br><br>    /** This function is used to calculate the height of the layout.<br>     *  [heightOfBubble] and [numberOfBubbles] is used to calculate the y position<br>     *  [topPadding] is the padding from top of the screen<br>     */<br>    fun getLayoutHeight(<br>        numberOfBubbles: Int,<br>        heightOfBubble: Int,<br>        topPadding: Int,<br>        density: Float<br>    ): Int<br>}</pre><ul><li>You can see the implementation here for the 1–2-1 bubble pattern: <a href="https://shorturl.at/akS46">https://shorturl.at/akS46</a></li><li>Detailed Explanation for the same can be found at <a href="https://shorturl.at/rAHX1">https://shorturl.at/rAHX1</a></li></ul><p>Now that we have that capability to get the x and y position for each bubble and also the total height of the bubbles, we just have to use them in our custom layout.</p><pre>@Composable<br>fun BubbleLayout(bubblePlacer: BubblePlacer, bubbles: List&lt;Bubble&gt;, topPadding: Int, modifier: Modifier = Modifier) {<br>    Layout(modifier = modifier, content = {<br>        repeat(bubbles.size) {<br><br>            Bubble(<br>                imageUrl = bubbles[it].imageUrl,<br>                subtitle = bubbles[it].title,<br>            )<br><br>        }<br>    }) { measurables, constraints -&gt;<br>        val bubbles = measurables.map {<br>            it.measure(constraints)<br>        }<br>        val topPaddingPx = (topPadding * density).roundToInt()<br>        val bubbleHeight =<br>            bubbles[0].height // use the first bubble&#39;s height for reference to calculate layout height<br>        val layoutHeight = bubblePlacer.getLayoutHeight(<br>            bubbles.size,<br>            bubbleHeight,<br>            topPaddingPx,<br>            density,<br>        ) // calculate the layout height<br>        layout(constraints.maxWidth, layoutHeight) { <br>            bubbles.forEachIndexed { index, bubble -&gt;<br>                val position = bubblePlacer.place(<br>                    index,<br>                    constraints.maxWidth,<br>                    bubbleHeight,<br>                    bubbles[index].width,<br>                    topPadding = topPaddingPx,<br>                    density<br>                ) // find the position<br>                bubble.place(position.x, position.y) // place it<br><br>            }<br>        }<br>    }</pre><p>and we are done.</p><p>Creating an interface for placing the bubbles and calculating the layout’s height offers us several advantages:</p><ol><li>Separation of UI and Logic: The interface encourages a clear separation between the user interface and the underlying logic. This separation enhances maintainability and allows for the development of reusable layout-related components.</li><li>Scalability: The interface makes it possible to add new bubble patterns in the future without affecting the UI Part of code. For example we have if we want to implement a 2–1–2 pattern, we will just need to a create a new bubble placer and pass it to our custom layout.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*d0wqvQGgkNatXBb8O_rt3w.png" /><figcaption>Example showing 2 different type of layout patterns.</figcaption></figure><p><strong>Final Product </strong>🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*jGB80ifL4En1rgctBnbFqA.gif" /></figure><p>Credits — <a href="https://medium.com/u/62d308161754">Arun Sharma</a> <a href="https://medium.com/u/1bf9bdb89775">Raj Gohil</a> Thank you for helping and guiding while working on this project.</p><h4>Resources</h4><p><a href="https://developer.android.com/jetpack/compose/layouts/custom">https://developer.android.com/jetpack/compose/layouts/custom</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecf7d010ca8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/building-the-whattoeat-experience-on-android-8ecf7d010ca8">Building the WhatToEat Experience on Android</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>