<?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 Muhammad Youssef on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Youssef on Medium]]></description>
        <link>https://medium.com/@Myyousseff?source=rss-ff2474255a49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y6hXb1aPubYjwLOvf2StVw.jpeg</url>
            <title>Stories by Muhammad Youssef on Medium</title>
            <link>https://medium.com/@Myyousseff?source=rss-ff2474255a49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:32:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Myyousseff/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[Coherence Without Comprehension: Inside How AI Writes Language]]></title>
            <link>https://medium.com/@Myyousseff/coherence-without-comprehension-inside-how-ai-writes-language-30f1bc32e17e?source=rss-ff2474255a49------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f1bc32e17e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Muhammad Youssef]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 12:02:37 GMT</pubDate>
            <atom:updated>2026-01-24T12:02:37.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdZgscydcR7pUXrOw0Q5Ag.png" /></figure><p>You type a complex question into ChatGPT or Claude. The cursor blinks. Then language begins to appear — measured, coherent, sometimes even poetic. Clauses follow clauses. Conclusions seem to emerge with intent. It feels as though something on the other side has already seen the end of the thought and is now walking you toward it.</p><p>That impression is false.</p><p>The model does not know what it will say. Not the paragraph. Not the sentence. Not even the next word. There is no internal narrative, no latent plan waiting to be revealed. At every step, the system is confronted with a single question: <strong>given everything so far, what “word” is most likely to come next?</strong></p><p>What you are witnessing is not intelligence as we understand it. It is coherence without comprehension. Structure emerging from a process that never plans, never reflects, and never understands. The gap between those two realities is where the illusion lives.</p><p>To see why this illusion is so convincing, we have to look at what actually happens between the moment you hit <em>Send</em> and the moment the first word appears.</p><h3>TL;DR</h3><p>By the end of this article, you’ll be able to look at a prompt and predict how the model will respond to it and why. You’ll see what makes a prompt collapse into noise, what makes another lock the model into clarity, and how the same system can feel intelligent or incompetent depending on how you engage it.</p><p>But to get there, we first need to strip away the illusion and examine the machinery underneath.</p><h3><strong>From Prompt to Text: The Language Generation Pipeline</strong></h3><p>When you press <strong>Send</strong>, nothing starts “thinking.”<br>Instead, your prompt enters a sequence of transformations — each step moving it further away from human language and closer to raw computation.</p><p>First, the sentence is broken into pieces.<br>Those pieces are <strong>translated into numbers</strong>.<br>The numbers are <strong>compared to establish context</strong>.<br>Every possible continuation is <strong>evaluated and scored</strong>.<br>One option is <strong>chosen and locked in</strong>.</p><p>That single choice is then fed back into the system, and the entire sequence runs again.</p><p>This loop repeats once for every word that appears on your screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tB33ftF_-xGysNPLM9Rtg.png" /></figure><p>In technical terms, the process consists of five phases:</p><ol><li><strong>Tokenization: </strong>Language is fractured into discrete units that the model can operate on.</li><li><strong>Embeddings: </strong>Those units are lifted out of text entirely and placed into a numerical space of meaning.</li><li><strong>The Transformer: </strong>Context is processed through layers of attention, deciding what matters and what doesn’t.</li><li><strong>Probabilities: </strong>Every possible continuation is evaluated and scored.</li><li><strong>Sampling: </strong>A single option is selected, fixed in place, and fed back into the system.</li></ol><p>Nothing here runs once. There is no final pass, no overview, no plan.<br>Only a loop executed at scale, where language emerges one <strong>irreversible choice at a time</strong>.</p><p>To make sense of how such a simple loop can produce such convincing language, we need to slow it down and examine each phase in isolation. Starting with the very first transformation your text undergoes.</p><h3>1) Tokenization: Breaking Language Apart</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9QXJxYvF_kGEQrJxXA4gw.png" /></figure><p>The first myth to let go of is simple: <strong>tokens are not words</strong>.</p><p>Tokens are fragments. Sometimes a full word, sometimes a syllable, sometimes a piece of punctuation. Shaped by statistical efficiency, not by grammar. Tokenizers are trained in advance on vast collections of text to compress language as effectively as possible. Frequently occurring patterns are kept whole. Rarer or longer words are broken apart. “<em>The”</em> might be a single token; “<em>indistinguishable”</em> might become several.</p><p>All of this happens <strong>before</strong> the neural network is involved. No attention, no probabilities, no reasoning. Just a deterministic conversion from text to symbols. By the time the model begins operating, your prompt is no longer language at all. It’s a sequence of integers.</p><h3>2) Embeddings: Turning Symbols into Geometry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8sRMSAv5Pm2qt4kDdp2vQ.png" /></figure><p>Once language has been broken into tokens, an even less intuitive step follows: those numbers still carry no meaning.</p><p>A token ID is nothing more than an index in a lookup table. On its own, it encodes no semantics, no context, and no notion of relatedness. “<em>Dog”</em> and “<em>database”</em> might sit next to each other numerically or be separated by thousands of indices — the distance is arbitrary. If the model tried to operate on these token IDs directly, every token would be equally meaningless.</p><p>So the next step is not language processing. It’s a <strong>coordinate assignment</strong>.</p><p>Each token ID is mapped to a high-dimensional vector — a long list of numbers that places it at a specific position in space. This space is not linguistic. It is geometric. Distance, direction, and relative position are the only signals that exist.</p><p>Tokens that appear in similar contexts across massive amounts of text are placed near one another. Tokens that rarely co-occur drift farther apart. Over time, structure emerges — not because anyone defined it, but because statistical patterns enforce it.</p><p>This is how relationships take shape:</p><ul><li><em>Function</em>, method, and procedure fall into the same neighborhood.</li><li><em>Java</em>, Python, and JavaScript occupy adjacent regions.</li><li>Python the programming language and Python the snake are pushed far apart.</li></ul><p>No rules were written for this. No ontology was designed. The geometry formed itself. Once tokens become vectors, meaning is no longer symbolic. It becomes <strong>spatial</strong>.</p><ul><li>Similarity is represented as distance.</li><li>Analogy becomes direction.</li><li>Context becomes movement through this space.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*r2G9CKnCRWanLiC_.gif" /><figcaption>Reference: <a href="https://medium.com/@bateiko/vector-vs-embedding-whats-the-real-difference-e59b4775e2a1">https://medium.com/@bateiko/vector-vs-embedding-whats-the-real-difference-e59b4775e2a1</a></figcaption></figure><p>For the first time in the pipeline, the model has something it can actually operate on. These vectors — not words, not tokens — are what enter the transformer.</p><p>And this is where context begins to matter.</p><h3>3) The Transformer: Context Is a Mixing Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04rH8_1MZpAWv_O3MIBqPA.png" /></figure><p>By the time data reaches the transformer, language is already gone.</p><p>What the model receives is a sequence of vectors — points in a geometric space that encode meaning and similarity. But at this stage, each vector still stands mostly alone. It knows <em>what</em> it represents, but not <em>how it relates</em> to everything else around it.</p><p>The transformer’s job is to change that.</p><p>At its core, the transformer is not a reasoning engine. It doesn’t think or plan. Instead, it acts as a <strong>context mixer</strong>. Its role is to repeatedly take a set of vectors and rewrite each one in terms of all the others.</p><p>This happens through a mechanism called <strong>attention</strong>.</p><h4>3.1) Attention: Deciding What Matters</h4><p>For every token in a sequence, the transformer asks a simple question: “<em>Which other tokens should influence me right now — and by how much?”</em></p><p>For example: “The cat sat on the mat because it was tired.”</p><p>What does “<em>it”</em> refer to? Not the mat. The cat.</p><p>Humans resolve this instantly. The transformer does it numerically. When processing the vector for “<em>it”</em>, the attention mechanism assigns more weight to “<em>cat”</em> than to “<em>mat”</em>, even though “<em>mat”</em> appears closer in the sentence.</p><p>This isn’t logic in the human sense. It’s pattern recognition at scale. Across millions of examples, the model has learned that “<em>tired”</em> usually applies to living things, not objects.</p><p>Attention works by comparing vectors and assigning weights — numbers that determine how much each token influences every other token.</p><h4>3.2) Multi-Head Attention: Multiple Perspectives at Once</h4><p>This process doesn’t happen just once.</p><p>It runs <strong>in parallel</strong>, using what are called “<em>attention heads”</em>. Each head can focus on different kinds of relationships, such as:</p><ul><li>Grammatical structure</li><li>Semantic similarity</li><li>Positional cues</li></ul><p>One head might track subject–verb agreement. Another might follow references like “<em>it”</em> or “<em>they”</em>. Another might focus on the overall topic of the sentence.</p><p>None of these roles is predefined. They emerge naturally because different patterns help the model make better predictions.</p><h4>3.3) Depth: Building Meaning Layer by Layer</h4><p>After attention is applied, the vectors are updated. Each token now carries information not just about itself, but about its relationship to the entire sequence.</p><p>Then the process repeats.</p><p>Modern models stack dozens of these layers. Early layers tend to capture local structure. Later layers encode broader, more abstract context. With each pass, the representation becomes richer and more specific.</p><p>By the time the vectors leave the transformer, they no longer represent isolated meanings. They represent <strong>meaning in context</strong>. Not just “<em>cat”</em>. But “<em>this”</em> cat, in “<em>this sentence”</em>, for “<em>this purpose”</em>.</p><h4>3.4) What the Transformer Is Not</h4><p>There is no memory of past conversations here. No internal narrative. No global understanding of the prompt.</p><p>The transformer doesn’t know what it’s saying. It continuously rewrites vectors based on how they relate to one another. What feels like reasoning is the accumulated effect of repeated context mixing.</p><p>And once that mixing is done, the model moves on to its next step. It has to decide what comes next.</p><h3>4) Probabilities: Scoring the Future</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J99faT-vHIjODbcRRwXNeg.png" /></figure><p>Once the transformer finishes mixing context, its work is complete.</p><p>What comes out is a final set of vectors — each one encoding everything the model knows <em>at this moment</em> about the sequence so far. But nothing has been turned into text yet. There are no words. No sentences. Just numbers.</p><p>Now the model must answer a single question: “<strong>Given everything so far, what should come next?”</strong></p><p>To do that, it considers <strong>every possible next token</strong> in its vocabulary.</p><p>Not a handful.<br>Not the top few.<br><strong>All of them.</strong></p><p>For modern models, that can mean tens or even hundreds of thousands of possibilities.</p><h4>4.1) From Context to Scores</h4><p>The final transformer layer assigns a score to every possible next token. These scores are called <strong>logits</strong>.</p><p>On their own, logits don’t mean much. They’re just raw numbers:</p><ul><li>positive or negative</li><li>large or small</li></ul><p>To turn them into something usable, the model applies a mathematical function called <strong>softmax</strong>.</p><p>Softmax converts those raw scores into a probability distribution:</p><ul><li>Every token receives a probability</li><li>All probabilities sum to 1</li><li>Higher scores become higher probabilities</li></ul><p>At this point, the model still hasn’t chosen anything. It has simply produced a <strong>ranked list of possibilities</strong>.</p><p>For a prompt like “What is Python?”, the distribution might look something like this:</p><ul><li>“is” → 23%</li><li>“was” → 14%</li><li>“means” → 6%</li><li>thousands of other tokens → fractions of a percent each</li></ul><p>This is the core reality of language generation. The model does not decide what to say. It produces a <strong>probability distribution</strong> over what <em>could</em> come next.</p><h4>4.2) Plausibility, Not Truth</h4><p>This is also where a crucial limitation appears. The probabilities don’t represent truth. They represent plausibility.</p><p>The model has no built-in concept of correctness. It doesn’t verify facts or check consistency against reality. It simply assigns higher probability to sequences that look like things it has seen before.</p><p>This is why models can sound confident while being wrong.</p><p>When a model hallucinates, it isn’t lying. It’s selecting a high-probability continuation that happens to be false. The system knows how convincing answers are shaped. Not whether they’re correct.</p><p>At this stage, everything is still potential. Nothing has been committed. That happens next. The model must make a choice.</p><h3>5) Sampling: Committing to One Path</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxPMuJfwnDO1af_7S2X8fg.png" /></figure><p>Up to this point, nothing has actually been generated.</p><p>The model has:</p><ul><li>Broken text into tokens</li><li>Embedded them into geometry</li><li>Mixed context through attention</li><li>Scored every possible next token</li></ul><p>But it hasn’t <em>chosen</em> anything yet.</p><p>What it holds now is a probability distribution — a map of futures, each weighted by likelihood. Sampling is the moment where possibility collapses into reality. This is where the model commits.</p><h4>5.1) Choosing Is Not Picking the Best</h4><p>A common misconception is that the model always selects the most likely next token. It doesn’t.</p><p>If it did, every response would be painfully predictable. The same phrasing. The same structures. The same answers every time.</p><p>Instead, the model <strong>samples</strong> from the probability distribution.</p><p>That means:</p><ul><li>Highly probable tokens are <em>more likely</em> to be chosen</li><li>Less probable tokens are <em>still possible</em></li><li>Extremely unlikely tokens are effectively ignored</li></ul><p>This controlled randomness is what allows language to feel flexible rather than mechanical.</p><h4>5.2) Temperature: Controlling Risk</h4><p>Sampling behavior is shaped by a parameter called <strong>temperature</strong>.</p><p>Temperature adjusts how sharp or flat the probability distribution is before a token is selected.</p><ul><li><strong>Low temperature</strong> sharpens the distribution<br>- The top tokens dominate<br>- Outputs become focused, conservative, repetitive</li><li><strong>High temperature</strong> flattens the distribution<br>- Lower-probability tokens get more weight<br>- Outputs become more creative, but less reliable</li></ul><p>At temperature zero (theoretical), the model would always pick the single most likely token. At very high temperatures, generation becomes chaotic. Most real-world systems operate somewhere in between.</p><h4>5.3) Guardrails: Limiting the Space</h4><p>Additional techniques are often applied to prevent sampling from drifting into nonsense.</p><p>Two common ones:</p><ul><li><strong>Top-k sampling<br></strong>Only the top <em>k</em> most probable tokens are considered. Everything else is discarded.</li><li><strong>Top-p (nucleus) sampling<br></strong>Tokens are considered until their cumulative probability reaches <em>p</em> (for example, 90%). The tail is ignored.</li></ul><p>These methods don’t change what the model <em>knows</em>. They change which futures are allowed to choose from.</p><h4>5.4) One Token at a Time</h4><p>After sampling, a single token is selected. That token is appended to the sequence, then the entire process starts again:</p><ul><li>The new token is embedded</li><li>Context is remixed</li><li>Probabilities are recomputed</li><li>Another token is sampled</li></ul><p>There is no master plan. No outline. No awareness of where the sentence is going. Each step is local. Each choice depends only on what exists so far. What feels like a coherent paragraph is actually the result of hundreds or thousands of tiny commitments, made one token at a time.</p><h4>What Looks Like Intent Is Just Momentum</h4><p>The model does not know where it is heading. It doesn’t aim for conclusions. It doesn’t plan punchlines. It doesn’t hold goals in mind.</p><p>What emerges instead is <strong>statistical momentum</strong>. Once a direction is chosen, future probabilities reinforce it. Style stabilizes. Topic narrows. Coherence appears. Not because the model understands the destination. But because every step reshapes the landscape of what comes next.</p><p>And with that final commitment, language reappears. One token at a time.</p><h3>6) How to Leverage This When Using AI Agents</h3><p>Once you understand how models actually operate, a lot of “prompt magic” stops being magic.</p><ul><li>AI agents don’t reason globally.</li><li>They don’t plan end-to-end.</li><li>They don’t hold intent across time.</li></ul><p>They sample one token at a time, conditioned on the context you give them. That means <strong>your primary lever is context shaping</strong>.</p><h4>6.1) Control Behavior by Controlling Context</h4><p>Models don’t follow intent — they follow context. Clear structure, constraints, and framing sharpen the probability space and produce more reliable behavior than vague instructions ever will.</p><p><strong>Good example</strong></p><pre>You are a senior backend engineer.<br>Task: Review the following function for concurrency issues.<br>Constraints:<br>- Focus only on thread safety<br>- Ignore performance concerns<br>- Respond in bullet points</pre><p><strong>Bad example</strong></p><pre>Can you look at this code and tell me if it&#39;s okay?</pre><h4>6.2) Think in Trajectories, Not Prompts</h4><p>Early tokens set direction. The opening lines determine tone, depth, and structure. Treat prompts as the start of a trajectory, not a single instruction.</p><p><strong>Good example</strong></p><pre>We are writing a technical design review.<br>Audience: senior engineers.<br>Tone: precise, critical, neutral.<br><br>Begin by summarizing the core architectural tradeoff.</pre><p><strong>Bad example</strong></p><pre>Explain this architecture.</pre><h4>6.3) Use Examples to Collapse Ambiguity</h4><p>Examples reduce interpretation space. They show the model exactly which patterns to reinforce and which to ignore.</p><p><strong>Good example</strong></p><pre>Convert requirements into acceptance criteria.<br><br>Example:<br>Requirement: User can reset password<br>Acceptance Criteria:<br>- User receives reset email<br>- Link expires after 15 minutes<br>- Password meets policy<br><br>Now convert:<br>Requirement: User can export data</pre><p><strong>Bad example</strong></p><pre>Write acceptance criteria for this feature.</pre><h4>6.4) Break Tasks into Stable States</h4><p>Long, open-ended goals degrade output quality. Breaking work into phases keeps context sharp and reduces error accumulation.</p><p><strong>Good example</strong></p><pre>Step 1: Summarize the problem in one paragraph.<br>Step 2: List possible approaches.<br>Step 3: Evaluate tradeoffs.<br>Step 4: Recommend one option.<br>Proceed step by step.</pre><p><strong>Bad example</strong></p><pre>Figure out the best solution and explain everything.</pre><h4>6.5) Design for Correction, Not Perfection</h4><p>Models commit sequentially. Errors compound. Build feedback loops that reintroduce context and allow correction.</p><p><strong>Good example</strong></p><pre>Answer the question.<br>Then:<br>1. List your assumptions<br>2. Identify potential errors<br>3. Revise the answer if needed</pre><p><strong>Bad example</strong></p><pre>Give me the final answer.</pre><h4>6.6) Shape Context, Don’t Command Intelligence</h4><p>Agents aren’t planners or thinkers. They’re probabilistic systems responding to context. Precision beats authority.</p><p><strong>Good example</strong></p><pre>Here is the format you must follow:<br>- Assumption<br>- Reasoning<br>- Conclusion<br><br>If information is missing, say so explicitly.</pre><p><strong>Bad example</strong></p><pre>Be smart and figure it out.</pre><h3>Final Thoughts</h3><p>What you’ve seen here isn’t a story about intelligence. It’s a story about mechanics.</p><p>From prompt to token, from token to vector, from vectors to probabilities, and from probabilities to a single irreversible choice. Language emerges without understanding, intention, or awareness. Coherence is not evidence of thought. It’s the result of structure, scale, and statistical momentum.</p><p>Once you understand this pipeline, AI stops feeling mysterious. You stop asking <em>“What does it know?”</em> and start asking <em>“What context am I shaping?”</em> The difference is subtle, but it’s where effective use begins.</p><p>There is no mind in the machine. But there is a system. And systems, once understood, can be guided.</p><h4>Thanks for reading through 🙌🏼. If you found this post useful, please share it through your circles.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f1bc32e17e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: The Anatomy of Jetpack Compose — The Stage is Set]]></title>
            <link>https://medium.com/@Myyousseff/part-1-the-anatomy-of-jetpack-compose-the-stage-is-set-5eab0bf54501?source=rss-ff2474255a49------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eab0bf54501</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Muhammad Youssef]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 13:11:07 GMT</pubDate>
            <atom:updated>2026-01-19T09:13:22.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Anatomy of Jetpack Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*m4qlBGT0ag1bEEnEtrDrqg.png" /></figure><h3>Introduction: Peeking Behind the Curtain</h3><p>Jetpack Compose is magical. You write a few lines of Kotlin code, and your UI springs to life — animated, reactive, and beautifully declarative. But… what if you could peel back the abstraction? What if you could follow a single @Composable through the rabbit hole — watching it morph at compile time, slip through memory-managed runtime systems, and finally breathe life into pixels?</p><p>This isn’t just a technical article. This is a journey — a deep dive into the compositional engine room where declarative code becomes dynamic UI.</p><p>And like any good film, we’ll build anticipation, peel back layers, and ultimately reveal the clever mechanisms that make Compose so powerful…and so fun to dissect.</p><p>Grab your popcorn. Let’s hit play.</p><h3>Overview: Setting the Stage</h3><p>Jetpack Compose didn’t just simplify Android UI development — it reinvented the rules of the game. With its declarative paradigm, Compose invites us to describe what the UI should look like, while it takes on the responsibility of figuring out how to make it happen efficiently. But behind that elegant simplicity lies a symphony of deeply intricate systems, finely tuned for performance, state-awareness, and composability.</p><p>As we dim the lights and roll the opening credits, let’s meet the three core components that make this all possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ho154y0j5GCRc31UH9lLDw.png" /></figure><ul><li><strong>Compose (UI API Surface)</strong>: This is the face of the framework, the place where you, the developer, sketch UI with declarative brushstrokes. Text, Column, Button, LazyColumn — these are the actors you direct on stage, but the real drama unfolds backstage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKfvjs0tY9ttiluAQv4-GQ.png" /></figure><ul><li><strong>Compose Compiler</strong>: The unsung metaprogramming <em>(code that writes code)</em> hero. Think of it as the stage crew that transforms your script — the @Composable functions — into optimized, lower-level instructions. It injects code to track changes, trigger recompositions, and decide what should be skipped altogether.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbjPICIcYjUNMu_ncXU2jA.png" /></figure><ul><li><strong>Compose Runtime</strong>: The stage director, ensures that every note plays at the right time and in the proper sequence. It listens intently for any state changes, keeping meticulous track of reads and writes. When the music shifts, it cues only the relevant instruments (composables) to play again. It maintains and manipulates memory structures like the mysterious yet powerful SlotTable, a central memory structure where Compose stores and manages the state of your UI (more on that later), where the lifeblood of recomposition flows.</li></ul><p>We won’t just talk theory — we’re going to bring this all to life through a real-world case study. A single composable, deceptively simple on the outside, will take us on a journey through the veins of the framework, revealing what really happens when Compose springs into action.</p><p>Ready? The curtain’s about to rise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*e2T_4dFARYJhrLuG.gif" /></figure><h3>Case Study: The Living Greeting</h3><p>Imagine you’re writing a simple UI: a greeting message that slowly reveals a name, letter by letter, like a suspenseful reveal in a movie, showcasing Compose’s ability to handle dynamic UI updates. It’s a task that seems simple on the surface, yet, beneath the quiet, ticking seconds, there’s a whirlwind of activity. This is where we begin our journey into Jetpack Compose.</p><p>At first glance, the composable might look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93830d03d4f4d06a96d50b87ab0ea79/href">https://medium.com/media/e93830d03d4f4d06a96d50b87ab0ea79/href</a></iframe><p>This humble Greeting composable will slowly reveal the name, letter by letter, thanks to the LaunchedEffect and remember mechanisms. It’s a simple interaction, but as we zoom in on its inner workings, we’ll uncover how Compose optimizes everything — from state management to recomposition skipping.</p><p>But here’s the twist: as each letter of the name is revealed, it triggers recomposition, and yet, Compose is smart enough to avoid redundant updates. It knows when to skip when to recompose, and how to do all this efficiently. So, what’s really happening under the hood when you invoke this seemingly trivial composable?</p><p>Let’s dive in deeper and uncover what’s going on.</p><h3>Compose Compiler: The Metaprogramming Beast</h3><p>Imagine this: you’ve just written a composable function, something simple like Greeting. It looks clean and straightforward in your Kotlin file. But what happens behind the scenes, when you annotate that function with @Composable, is where the real magic begins.</p><p>Unlike typical Kotlin code, where reflection or runtime instrumentation would usually step in to modify the behavior, the Compose Compiler works a bit differently. This is no ordinary compiler — it’s a powerful Kotlin compiler plugin that intercepts your composable code at compile time and transforms it into something far more powerful, injecting code for state tracking and recomposition management. It’s like a hidden member of the stage crew behind the scenes, reworking your script before it’s even performed on stage.</p><p>At this point, your code undergoes a transformation so subtle, yet so profound, that it remains almost invisible in the final app. But as we peel back the layers, we can begin to see how this intricate process unfolds.</p><h4>What Actually Happens?</h4><p>Let’s take a closer look at the Greeting function, the one we’ve been working with. At first glance, it looks simple and declarative. But when you annotate it with @Composable, it morphs into something entirely different behind the scenes.</p><p>What once was:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c19c4edca22875f8615bce85f59223a/href">https://medium.com/media/9c19c4edca22875f8615bce85f59223a/href</a></iframe><p>…is now rewritten by the compiler into something far more complex and optimized:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c8e280adc3ee3fdf95a9cbf1521c2b/href">https://medium.com/media/78c8e280adc3ee3fdf95a9cbf1521c2b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*-EFhqR5HTB9FW5XH.gif" /></figure><h3>The Transformation Process</h3><p>At first, this might seem like just adding some arguments to your function. But the real change is more profound. The Compose Compiler is doing far more than just tweaking function signatures. It injects special logic into the composable to make it recomposition-aware and optimize how the state is handled. Here’s how:</p><h4>1) Recomposition Boundaries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*7DCBxkabPCcvu7VDPsE21w.png" /></figure><p>The compiler inserts calls to startRestartGroup() and endRestartGroup(). These are the markers that define the recomposition boundaries. Think of them as the ropes around a wrestling ring — clearly marking the area where all the action happens, so when the bell rings for a rematch (aka recomposition), the system knows exactly where to jump back in. When the state changes, the composable is &quot;restarted,&quot; but only the part of the UI that&#39;s affected gets rerun. It&#39;s efficient, intentional, and orchestrated with precision.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/490535315c3fbd0391382d76eabd1eca/href">https://medium.com/media/490535315c3fbd0391382d76eabd1eca/href</a></iframe><h4>2) Tracking Stable vs Unstable Parameters</h4><p>Not all parameters are treated equally in Compose. Some are stable (like name in the Greeting function) and some are unstable. The compiler uses this information to skip recomposition for stable parameters, making the process far more efficient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead8a966b64eb353aafc6158dfea239c/href">https://medium.com/media/ead8a966b64eb353aafc6158dfea239c/href</a></iframe><p>While this function doesn’t exist exactly like this in the source code, it conceptually reflects how Compose handles value stability. In reality, Compose determines stability using a combination of <strong>compiler-inferred metadata</strong> (such as @StabilityInferred) and <strong>annotations</strong> like @Stable and @Immutable. At runtime, stability checks are guided by the StabilityChecker utility, which inspects class-level metadata to decide whether a value can be considered stable. This metadata is embedded by the Compose compiler during code generation.</p><p>If a value is marked stable and hasn’t changed, the Compose runtime can skip the corresponding recomposition group using methods like Composer.changed() and Composer.skipToGroupEnd(). This allows Compose to efficiently recompose only the parts of the UI that truly need updating — reducing unnecessary work and keeping rendering performance sharp.</p><h4>3) State Management with remember</h4><p>When you use remember in Compose, you might think it’s just a simple way to keep values across recompositions. But the compiler transforms this into a more nuanced process. Instead of just keeping the state, it wraps remember and mutableStateOf in compose.cache{} calls.</p><p>For instance, consider this:</p><pre>val state = remember { mutableStateOf(&quot;&quot;) }</pre><p>Under the hood, this is transformed into:</p><pre>val state = composer.cache { mutableStateOf(&quot;&quot;) }</pre><p>By doing this, the runtime can reuse the exact memory allocation for the state if the composition hasn’t changed. The cache is keyed by its slot position, ensuring that the memory location can be reused across recompositions. This avoids unnecessary memory allocations, ensuring performance remains optimal.</p><h4>4) Side Effect Registration</h4><p>In composables like LaunchedEffect and SideEffect (both annotated with @NonRestartableComposable), the compiler registers these side effects into “slots” that the Compose Runtime will later revisit. This ensures that actions like launching coroutines or running effects only happen when necessary, avoiding redundant operations.</p><p>@NonRestartableComposable prevents these composables from restarting unnecessarily during recomposition, which is crucial for side effects that should only execute once or when specific keys change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f6d9b85d4e75996ba9569077493926/href">https://medium.com/media/87f6d9b85d4e75996ba9569077493926/href</a></iframe><p>This ensures that coroutines launched withinLaunchedEffect, for example, are only executed when the key1 parameter changes, preventing unintended side effect triggers during recomposition.</p><h3>How Does This Benefit You?</h3><p>At the end of the day, the Compose Compiler ensures that your composables are more than just simple functions. It injects the necessary logic to enable:</p><ul><li><strong>Efficient Recomposition</strong>: Only the parts of the UI that actually need to change are recomposed. You don’t waste resources updating unaffected UI elements.</li><li><strong>State Persistence</strong>: The state is tracked and persisted intelligently, ensuring that composables don’t lose their context across recompositions.</li><li><strong>Performance:</strong> Through caching, memory management, and skipping unnecessary updates, Compose optimizes the entire process from start to finish, allowing developers to focus on building UI without worrying about low-level performance details.</li></ul><p>By the time the compiler is done with your composables, they’ve been transformed into something much more powerful than you originally wrote. It’s like watching a raw script evolve into a meticulously planned performance, complete with every detail accounted for.</p><p>But this is just the first layer of magic. The next step — the Compose Runtime, where the rubber meets the road — is where the real-time orchestration happens, ensuring that everything stays in sync, responds to state changes, and is rendered efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*uw57_hWm4A_B_1oP.gif" /></figure><p>Now that we understand how the Compose Compiler rewrites your code for maximum efficiency, it’s time to see how those transformed composables are orchestrated at runtime.</p><h3>Compose Runtime: The Orchestrator of Recomposition</h3><p>Let’s move from the crafty ingenuity of the Compose Compiler to the powerful engine that brings everything to life: the Compose Runtime. If the compiler is the hidden member of the stage crew who rearranges the script behind the scenes, the runtime is the stage director, ensuring that every note plays at the right time and in the right sequence.</p><p>The runtime is where the magic happens after your composables are compiled and set into motion. It’s a dynamic, state-driven system that doesn’t just update the UI when a change occurs but does so in an incredibly efficient and intelligent manner. The runtime accomplishes this feat by using structures like the SlotTable. The beauty of the Compose Runtime lies in its ability to orchestrate every action in response to state changes while maintaining performance.</p><p>But how does the runtime achieve this? What goes on under the hood that makes it so smooth, so efficient, and, most importantly, so responsive?</p><h3>What Actually Happens?</h3><p>Here’s how the runtime pulls off its performance magic:</p><h4>1) State Observation</h4><p>Imagine having a backstage crew that’s constantly watching every interaction, every change in your UI, and reacting only when necessary. In the world of Jetpack Compose, this “crew” is the Compose Runtime, and its job is to carefully track every state change, updating only the parts of the UI that need it.</p><p>Here’s where things get really interesting. The moment you declare something like:</p><pre>var greetingText by remember { mutableStateOf(&quot;&quot;) }</pre><p>So what happens behind the scenes? The remember function is doing more than meets the eye. Internally, it’s not just holding onto the value; it’s associating that value with a slot, a memory location that Compose uses to track the state across recompositions. When the state doesn’t change, the runtime doesn’t waste time recreating everything; it simply reuses the memory slot that holds that value.</p><p>Check out this example of what’s happening behind the scenes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb4bf4a4f0d1321c34ef1023df9dc1bf/href">https://medium.com/media/fb4bf4a4f0d1321c34ef1023df9dc1bf/href</a></iframe><p>This is where the magic happens: cache ensures that the value gets stored in a specific memory slot. If the state hasn’t changed, the slot remains untouched. If it has, the slot is updated — just like replacing a note in an orchestra, without disrupting the entire performance.</p><p>Here’s how it works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2d654725510cc2106726d899948f6a/href">https://medium.com/media/1e2d654725510cc2106726d899948f6a/href</a></iframe><p>By using slots, Compose guarantees that only the relevant parts of the UI are updated when a state changes. In the case of greetingText, it ensures that only the UI elements depending on that value are affected, keeping performance sharp and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*EmZF3zCLa_LryQ7sEc5ctQ.png" /></figure><p>So, the next time you change a state in Compose, remember: it’s not just about changing a variable. It’s about a carefully orchestrated update to just the right part of the UI, thanks to the power of slots and state tracking. It’s this level of precision that allows Compose to be both powerful and efficient.</p><h4>2) SlotTable and Slot Reuse</h4><p>Meet the SlotTable. A data structure so central — so cunning — it quietly orchestrates the entire recomposition process without most developers ever knowing its name.</p><p>This isn’t just any data structure. It’s Compose’s secret ledger — a highly optimized, tree-like memory bookkeeper that records where every piece of your UI has lived and should live during recomposition. The tree-like structure is beneficial as it mirrors the hierarchical structure of your UI, allowing for efficient updates to specific parts of the UI tree. While your code might feel stateless and ephemeral, the SlotTable is where permanence is forged.</p><p>So how does this work? Let’s start with a bit of magic: when a composable is first executed, the Compose Runtime walks through it, writing down entries in the SlotTable. These entries capture everything from parameters to remembered state values and even effect registrations. Then, when recomposition time comes, it revisits those entries — not to rebuild, but to reuse, skip, or update.</p><p>To understand better, let’s peel back the curtain.</p><h3>Anatomy of a Slot</h3><p>A slot is an abstract representation of a location in the composition tree. Each slot stores data: maybe a remembered value, maybe a group node, maybe nothing. But collectively, these slots form a SlotTable, which is essentially a sequence of grouped slots, enabling Compose to surgically recompose only what’s changed.</p><p>In the actual implementation, Compose uses a sophisticated array-based structure for performance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/814afa371651ee35488d316a0e973d21/href">https://medium.com/media/814afa371651ee35488d316a0e973d21/href</a></iframe><p>Compose doesn’t use plain data classes. Instead, it employs a flat array-based structure for blazing speed — insertions, reads, and skips all happen in <em>O(1)</em> or near <em>O(1)</em> time.</p><p>The implementation includes more sophisticated components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e11b68d602a26581961e613d64505a/href">https://medium.com/media/b8e11b68d602a26581961e613d64505a/href</a></iframe><p>Each group in the groups array helps Compose identify a composable&#39;s location and content. Think of it like a GPS tracker for UI logic. When Compose starts recomposition, it consults this map:</p><ul><li>Has this group moved?</li><li>Is the remembered value still valid?</li><li>Can this be skipped entirely?</li></ul><p>If the answer is yes, it skips the recomposition entirely. If no, it recalculates, rewrites that slot, and moves on.</p><h4>Slot Reuse: The Art of Not Starting Over</h4><p>When you call remember { mutableStateOf(…) }, Compose doesn&#39;t just blindly create a new state holder. It checks the current slot position in the SlotTable. If there&#39;s a cached value and the slot group hasn&#39;t changed, it reuses it. If not, it writes a new one.</p><p>Here’s how reading and writing to the SloteTable actually happens under the hood:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9acfad03f4f70b42d073b89d517781a0/href">https://medium.com/media/9acfad03f4f70b42d073b89d517781a0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a60fd2947607ed84c12ccd433aff9cb2/href">https://medium.com/media/a60fd2947607ed84c12ccd433aff9cb2/href</a></iframe><p>This isn’t just caching — this is structured memory reuse with surgical precision.</p><p>And during recomposition, something wild happens: Compose moves a reader over the SlotTable and creates a writer that selectively replaces what needs to change. All while maintaining consistent group IDs and slot anchors using the Anchor class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c89bd6bf245552d3ea33b51c107a5f25/href">https://medium.com/media/c89bd6bf245552d3ea33b51c107a5f25/href</a></iframe><p>These anchors, which are tied to the group IDs, allow Compose to maintain references to specific groups even as the table changes during recomposition, ensuring stability and efficiency in the UI update process. They are a way to keep track of where in the slot table a specific composable exists.</p><h4>Why It’s Brilliant</h4><p>The SlotTable is what allows Compose to:</p><ul><li>Reuse the exact memory locations for values like remember across recompositions.</li><li>Skip entire sections of the composition tree when inputs haven’t changed.</li><li>Restore UI efficiently after configuration changes or recomposition skips.</li></ul><p>In our “Living Greeting” example, the SlotTable ensures that only the newly revealed letters trigger recomposition, avoiding unnecessary updates to the entire greeting.</p><p>Without SlotTable, Compose would have to rerun every composable, reinitialize every state, and relaunch every side effect. That’s not just wasteful — it’s unacceptable for modern UIs.</p><p>As UI complexity grows, Compose needs stable anchors to maintain efficiency. This is where Group Introspection and Anchor Stability come into play.</p><p><strong>Group Introspection</strong> empowers Compose to inspect the <em>shape</em> of a composition group without re-running its code. Instead of blindly executing the group, Compose analyzes its <strong>keys and structural boundaries</strong>, effectively building a <em>blueprint</em> of the UI. This lightweight inspection enables Compose to decide whether a group requires recomposition — without touching a single composable inside it.</p><p>By analyzing group keys and boundaries, it can:</p><ul><li>Determine if a group can be skipped entirely</li><li>Predict the impact of state changes on the composition tree</li><li>Optimize memory allocation for stable structures</li></ul><p>Anchor Stability is the mechanism that ensures consistent identification of UI elements across recompositions. When working with lists or dynamic content, stability is crucial for performance.</p><p>Consider a LazyColumn with items that might change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/447065599cb546c3a8c6a11bd683d9e9/href">https://medium.com/media/447065599cb546c3a8c6a11bd683d9e9/href</a></iframe><p>Without stable anchors, recomposition might unnecessarily recreate all items when only one changes. With anchor stability, Compose can:</p><ul><li>Track each item’s position with a unique key</li><li>Reuse existing compositions when items remain the same</li><li>Only recompose items that have actually changed</li></ul><p>This is achieved through the key() function, which creates stable anchors in the SlotTable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f5b5e19859032403ff26b09a414897f/href">https://medium.com/media/3f5b5e19859032403ff26b09a414897f/href</a></iframe><p><strong>Visual Representation:</strong></p><p>Imagine the SlotTable as a series of slots, each potentially holding data for a UI element. The key() function associates each user.id with a specific slot or anchor within this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*bHzFCZWEhrBVviyU4CCThQ.png" /></figure><p>Internally, these keys become persistent anchors in the SlotTable, allowing precise targeting during recomposition, even when items move around in a collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*g-rklpCZB3gyMQgg.gif" /></figure><h4>A Real-World Analogy</h4><p>If Compose were a Broadway production, your <strong>composables would be actors</strong> reading lines. The <strong>Compose Compiler is the stage crew</strong> rewriting the script behind the scenes.</p><p>And the <strong>SlotTable? It’s the stage manager’s clipboard</strong> — tracking exactly where each actor should stand, what prop they should hold, and whether they even need to be on stage at all tonight.</p><p>And we’re only scratching the surface. In the next act, we’ll follow how recomposition navigates through the SlotTable with surgical precision, using a tree-walk algorithm to determine what changes and what stays frozen in time.</p><p>Lights down. Spotlight on the Recomposer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*k-UJxF-hM1XIwXFP.gif" /></figure><h3>3) The Recomposer: Compose’s Stage Director</h3><p>We’ve met the SlotTable — the silent archivist of the state. But even the best records are useless without someone to interpret them. That’s where the Recomposer steps in.</p><p>If the <strong>SloteTable is the stage manager’s clipboard</strong>, the <strong>Recomposer is the director</strong> mid-performance — watching, cueing, and deciding exactly who gets to step into the spotlight during recomposition, and who can safely remain in the shadows.</p><p>At a high level, the Recomposer is responsible for driving changes through the composition system based on state changes or external triggers (like LaunchedEffect, mutableStateOf, or snapshotFlow). But the magic lies in how it choreographs these changes in lockstep with theSlotTable, using a tree-walk algorithm.</p><h4>The Dance of Recomposition</h4><p>Here’s the sequence that happens when a state changes in Compose:</p><ol><li>A state holder (e.g. MutableState) updates.</li><li>It notifies the Snapshot system (a system that manages concurrent read/write access to the state).</li><li>The Snapshot marks certain composition scopes as invalid.</li><li>The Recomposer picks up the invalid scopes and begins a recomposition pass.</li><li>It walks the SlotTable with a SlotReader, comparing group keys.</li><li>It selectively executes only the functions whose inputs have changed.</li><li>The results are written back into the SlotTable via the Composer.</li></ol><p>Let’s peek into the code.</p><h4>The Recomposer’s Loop (Yes, It’s a Loop)</h4><p>Think of the Recomposer as an ever-alert film editor, constantly scanning for scenes (composables) that need reshooting. It doesn’t just sit around waiting — it’s in a coroutine loop, waiting for signs of change, like a detective watching for clues.</p><p>The real loop lives in this method:</p><pre>suspend fun runRecomposeAndApplyChanges()</pre><p>Inside, Compose tracks any state that was invalidated (through Snapshot.apply() or user actions) and queues up compositions that need to be re-run. It’s a long coroutine, spinning quietly in the background like a heart monitoring system.</p><p>Internally, it orchestrates all this through:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3147b0aaa22d098041888b000975e9/href">https://medium.com/media/2c3147b0aaa22d098041888b000975e9/href</a></iframe><p>The recordComposerModifications() method collects any snapshot changes and marks which compositions need to be updated. Then, during withFrameNanos, the Recomposer enters a trace block (a section of code that is being measured for performance or debugging), triggering actual recomposition through performRecompose() and applying the result.</p><h4>The Composer: Reading, Writing, and SlotTable Magic</h4><p>The Composer is your runtime tree-walker, your loyal assistant with a clipboard during a scene reset. It walks through the composition tree using <strong>group keys</strong> (unique identifiers for composable function calls), compares parameter stability, and decides what to recompute or skip.</p><p>Let’s say you write this:</p><pre>val name = remember { mutableStateOf(&quot;Muhammad&quot;) }<br>Text(&quot;Hello, ${name.value}&quot;)</pre><p>When name.value changes:</p><ul><li>The Recomposer marks the group that produced the Text.</li><li>The Composer enters that group in the SlotTable.</li><li>If inputs haven’t changed, it may issue askipGroup(), which tells the slot table to skip forward to the end of the group.</li><li>Otherwise, it re-invokes Text() and rewrites that part of the slot memory.</li></ul><p>Internally, it operates roughly like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca0194b07cebc737762b7b5a8a43ef6/href">https://medium.com/media/1ca0194b07cebc737762b7b5a8a43ef6/href</a></iframe><p>These calls (<strong>startGroup</strong>, <strong>endGroup</strong>, <strong>skipGroup</strong>) are critical — they define structural regions of your UI and enable <strong>slot reuse</strong>, making Compose incredibly performant. You don’t rebuild the entire UI — you surgically patch the relevant bits.</p><h4>Structural Reuse: Why It’s Fast</h4><p>Imagine you have:</p><pre>if (userLoggedIn) {<br>    Text(&quot;Welcome&quot;)<br>} else {<br>    Text(&quot;Please log in&quot;)<br>}</pre><p>When userLoggedIn changes, Compose doesn’t re-run the entire function. Instead, the runtime checks the group keys (unique identifiers for each composable call within the composition tree) and only re-invokes the composable block that needs to change.</p><p>This is possible because Compose treats the UI like a persistent tree structure, stored within the SlotTable, not like ephemeral function calls. The SlotTable, along with anchors and keys, remembers exactly where each piece lives — enabling surgical recompositions.</p><h4>A Step Ahead: Anticipating Future State</h4><p>Here’s a cool trick: Compose doesn’t always wait until the next frame to start work. It can predictively begin recomposition during idle time or in anticipation of animation frames. This allows Compose to start computations before they are needed, helping maintain buttery-smooth 60fps animations, even during complex state transitions. This proactive recomposition ties into the Recomposer’s loop, which continuously monitors for state changes and anticipates future UI updates.</p><p>All of this — the slot bookkeeping, the stability checking, the recomposition loop — comes together like a symphony. It’s not just functional programming; it’s orchestrated performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*zAU4GYMMBdtRnZkK.gif" /></figure><p>But even the most perfectly rehearsed performance needs to be seen and heard by an audience. Our stage is set, the actors know their lines, and the director has called for action. Now, how does all this meticulously managed state translate into the visual spectacle we call a UI? <br>That’s where the Applier System steps in.</p><p>We’ve seen how Compose choreographs the internal mechanics of recomposition with breathtaking precision. But the story isn’t over. <br>How does this logical structure of slots and keys finally become the pixels we see on the screen?</p><h3>The Applier System: Jetpack Compose’s Bridge to Reality</h3><p>Think of the Applier System as the backstage crew of a theater production, turning abstract directions into a visible set. In Jetpack Compose, it serves as the bridge between our declarative UI descriptions and the actual pixels rendered on the screen.</p><p>While we’ve explored how Compose tracks state, manages recomposition, and optimizes performance through its SlotTable, there’s still a crucial piece missing: how do these virtual representations become actual UI elements on screen? Enter the Applier system.</p><p>The Applier is Compose’s abstraction layer that bridges the gap between the composition tree and the actual rendering system. Think of it as the stage crew transforming the director’s vision into a physical set.</p><p>At its core, the Applier is responsible for:</p><ol><li><strong>Creating UI Elements</strong>: When a composition introduces new nodes, the Applier instantiates the corresponding UI elements.</li><li><strong>Updating UI Elements</strong>: When properties change during recomposition, the Applier applies those changes to existing UI elements.</li><li><strong>Removing UI Elements</strong>: When nodes are removed from the composition, the Applier cleans up their corresponding UI elements.</li></ol><p>The true power of the Applier lies in its platform-agnostic design. The same composition logic can target multiple rendering systems through different Applier implementations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/421f0d3ec497cceaecb2dad3e9c99579/href">https://medium.com/media/421f0d3ec497cceaecb2dad3e9c99579/href</a></iframe><p>On Android, the primary Applier implementation transforms compositions into either:</p><ul><li><strong>Android View nodes (through the AndroidComposeView)</strong><br>This implementation leverages the traditional Android View system, allowing Compose to integrate seamlessly with existing Android UI components.</li><li><strong>Skia canvas draw operations (through the SkiaLayer)<br></strong>This implementation enables direct drawing onto a Skia canvas, providing more control and flexibility for custom rendering.</li></ul><blockquote>The generic type <em>&lt;N&gt;</em> represents the type of node that the Applier works with. This node type varies depending on the rendering backend. For example, on Android, <em>&lt;N&gt;</em> can represent an Android View or a Skia drawing operation</blockquote><p>Here’s how it works in practice:</p><pre>@Composable<br>fun Greeting(name: String) {<br>    Text(&quot;Hello, $name&quot;)<br>}</pre><p>When this composable runs:</p><ol><li>The composition system creates a node for the Text</li><li>The AndroidComposeView’s Applier creates a text layout object</li><li>The Applier sets up the text content, styling, and layout properties</li><li>When rendered, the Applier triggers draw calls to display the text</li></ol><p>The Applier’s design enables Compose to run on multiple platforms while maintaining the same programming model. This is why Compose can target Android, Desktop, Web, and even custom rendering systems without changing the core composition logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*8vganTTPYrbBHakcgwYBhg.png" /></figure><h3>Conclusion: The Symphony of Composition</h3><ol><li><strong>Declarative Expression</strong>: Compose lets developers describe what the UI should look like, not how to build it.</li><li><strong>Intelligent Recomposition</strong>: Through compiler transformation, state tracking, and the SlotTable, Compose minimizes work by only updating what’s changed.</li><li><strong>Structural Stability</strong>: The Applier system, group introspection, and anchor stability ensure consistent, efficient UI updates across platforms.</li></ol><p>What makes Compose truly revolutionary isn’t just that it simplifies UI development — it’s that it does so while maintaining exceptionally high performance. By transforming functions at compile time, strategically managing memory, and surgically applying updates, Compose achieves a level of efficiency that would be nearly impossible with manual optimization.</p><p>Looking ahead, the architecture of Compose opens exciting possibilities:</p><ul><li><strong>Cross-platform expansion</strong>: Thanks to its platform-agnostic architecture, Compose can extend its programming model beyond Android, iOS, Desktop, and Web — potentially unlocking new environments in the future.</li><li><strong>Compiler optimizations</strong>: As the Compose compiler evolves, we can expect even more sophisticated transformations that further reduce boilerplate and improve performance.</li><li><strong>Enhanced tooling</strong>: Deeper integration with Android Studio and development tools will likely provide better visualization and debugging of composition internals.</li></ul><p>The next time you write a simple @Composable function, remember the incredible journey it takes — from compile-time transformation to runtime optimization — before it finally appears on the screen. Jetpack Compose isn’t just a UI framework; it’s a testament to the power of thoughtful abstraction in modern software development.</p><p><strong>Disclaimer:</strong> Compose internals are subject to frequent change. Code examples illustrate current behavior, which may evolve.</p><p>Thanks for reading through 🙌🏼. If you found this post useful, please share it through your circles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eab0bf54501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Journey Of Launching An Android Activity]]></title>
            <link>https://medium.com/@Myyousseff/the-journey-of-launching-an-android-activity-9b64e11dc157?source=rss-ff2474255a49------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b64e11dc157</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Muhammad Youssef]]></dc:creator>
            <pubDate>Sun, 06 Jan 2019 17:16:31 GMT</pubDate>
            <atom:updated>2019-07-14T14:31:08.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DB9FknFxLxNCrwSFJvHTTw.png" /></figure><blockquote>What happens inside Android, stays inside Android.</blockquote><p>You are an Android developer; You know very well how to launch an Android activity and by the time you are reading this you probably did it zillion times. But have you ever wondered why do we do it this way? Why do we use intents to create an activity object? What makes an Activity object so unique and different from any other java object? After all, it’s a java object right? Then where, when and how the “<em>new Activity()”</em> statement actually gets executed?! What happens before an activity gets created? In this article we take a glance at the behind-the-scenes of launching Android activities. I assume that you’re already familiar with Java programming language, OOP principles and Android development fundamentals.</p><p>Let’s start by creating a project with an activity and override the <a href="https://en.m.wikipedia.org/wiki/Default_constructor">default constructor</a>. The simplest way to check the path to a constructor is by placing a breakpoint to it. It will enable us to walk through all the calls and explore the implemented code to find exactly what we want. Executing the project will result into the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQnI3GLHyaqzqs2qttJcSg.png" /><figcaption>Android studio debugger</figcaption></figure><blockquote>In any Unix-based operating system, the first thing the kernel does is to execute <a href="https://en.m.wikipedia.org/wiki/Init">init process</a>. Init is the root/parent of all processes executing on Linux.</blockquote><p>As we can see at the very bottom of the debugger frames, Android internally calls something called <a href="https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/com/android/internal/os/ZygoteInit.java#70">ZygoteInit</a><strong>.<br></strong>Wait what?! <br>Yes, as the name implies, it’s the very beginning for the rest of the Android application. It gets its name from dictionary definition: “<em>It is the initial cell formed when a new organism is produced</em>”.</p><p>Android at its core has this process called <a href="https://elinux.org/Android_Zygote_Startup">Zygote</a>, which starts up at <a href="https://en.m.wikipedia.org/wiki/Init">init</a>. It’s a special Android OS process that enables shared code across Dalvik/Art VM. This process is a “Warmed-up” process, which means it starts by preloading all classes and resources which an app may potentially need at runtime into the system’s memory. It then forks itself to start a well managed process called <a href="https://android.googlesource.com/platform/frameworks/base/+/7d276c3/services/java/com/android/server/SystemServer.java#848">SystemServer</a><strong> </strong>which starts initializing all core platform services it houses. One of the core services that gets started by SystemServer that we are particularly interested in<strong> </strong>is <a href="https://android.googlesource.com/platform/frameworks/base/+/4f868ed/services/core/java/com/android/server/am/ActivityManagerService.java#231">ActivityManagerService</a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*ZkByvPGBmvH6zoMT.gif" /></figure><h3>ActivityManagerService</h3><p>This service is where all the magic happens. It is responsible for a new Activity thread process creation, maintenance of the Activity lifecycle and managing the Activity stack. At it’s startup, it performs three main steps:</p><h4>1- Collect Target Activity Information</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497ccb857763936bd23e637c326b6c7c/href">https://medium.com/media/497ccb857763936bd23e637c326b6c7c/href</a></iframe><p>The first step is to collect information about the target activity. This is done by calling <em>resolveIntent() </em>method on some hidden implementation for <a href="https://android.googlesource.com/platform/frameworks/base/+/483f3b06ea84440a082e21b68ec2c2e54046f5a6/core/java/android/content/pm/IPackageManager.aidl#45">IPackageManager</a> interface. After that the target information is saved back into the intent object to avoid re-doing this step.</p><h4>2- Check User Privileges</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0a41d70f25f28a34dbdb30342a67633/href">https://medium.com/media/f0a41d70f25f28a34dbdb30342a67633/href</a></iframe><p>Next important step is to check if user has enough privileges to invoke the target activity. This is typically done by calling <a href="https://android.googlesource.com/platform/frameworks/base/+/4f868ed/services/core/java/com/android/server/am/ActivityManagerService.java#7388"><em>grantUriPermissionLocked()</em></a><em> </em>and it does the following:</p><ol><li>Make sure the target package has a valid <a href="https://en.m.wikipedia.org/wiki/UID">UID</a> associated with it</li><li>Use the UID to check if the target package can grant permission to access uri by calling <a href="https://android.googlesource.com/platform/frameworks/base/+/4f868ed/services/core/java/com/android/server/am/ActivityManagerService.java#7227"><em>checkGrantUriPermissionLocked()</em></a></li><li>After making sure that the caller has all the permissions <a href="https://android.googlesource.com/platform/frameworks/base/+/4f868ed/services/core/java/com/android/server/am/ActivityManagerService.java#7360"><em>grantUriPermissionUncheckedLocked()</em></a> grants them to the target package as well</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*UtD_g0dZFkg615xl.gif" /></figure><h4>3- Activity object Instantiation</h4><p>Now to the juicy stuff, it’s time to check if the ProcessRecord already exists for the process. If the ProcessRecord is null, the ActivityManagerService has to create a new process to instantiate the activity (duh). The instantiation is done by the help of <a href="https://android.googlesource.com/platform/frameworks/base/+/d630f105e8bc0021541aacb4dc6498a49048ecea/core/java/android/app/ActivityThread.java#114">ActivityThread</a> class</p><p>At this point, all required permissions have been granted, all the information about the target activity have been stored in the intent object, and the system has made sure that the user has all the privileges to invoke the target activity. Now it’s time to instantiate and launch the target Activity. This phase can be divided into three sub-phases</p><p><strong>3.1- Get The Environment Ready</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8278503c55ed3e41702d48cb33c3bcc4/href">https://medium.com/media/8278503c55ed3e41702d48cb33c3bcc4/href</a></iframe><p>First things first, let’s get the environment ready. It does so by calling <a href="https://android.googlesource.com/platform/frameworks/base/+/d630f105e8bc0021541aacb4dc6498a49048ecea/core/java/android/app/ActivityThread.java#1758"><em>handleLaunchActivity()</em></a><em>. </em>This makes sure the configurations are up to date, the graphics environment is initialized and then initializes the <a href="https://android.googlesource.com/platform/frameworks/base/+/0e40462e11d27eb859b829b112cecb8c6f0d7afb/core/java/android/view/WindowManagerGlobal.java#39">WindowManager</a>.</p><p><strong>3.2- Retrieve The Previously Collected Information</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3c40c6c612322a6908e1c9abc5f4289/href">https://medium.com/media/d3c40c6c612322a6908e1c9abc5f4289/href</a></iframe><p>Now let’s retrieve the previously collected information such as ComponentName and create the baseContext to get prepared for the instantiation.</p><p><strong>3.3- The Instantiation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c09e2d7f512f62ddb706aeb74db45a2/href">https://medium.com/media/0c09e2d7f512f62ddb706aeb74db45a2/href</a></iframe><p>This is where it gets interesting. Android uses the help of <a href="https://stackoverflow.com/a/37632/7330512">java reflection library</a> to execute the <em>new Activity() </em>statement. It does so by calling <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Instrumentation.java#1211"><em>newActivity()</em></a><em> </em>method on the Instrumentation object which then delegates the action to theAppComponentFactory object by calling <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/AppComponentFactory.java#78"><em>instantiateActivity()</em></a><em> method.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*2wSWSjnavwHXkm06.gif" /></figure><p>After instantiation,<a href="https://android.googlesource.com/platform/frameworks/base/+/d630f105e8bc0021541aacb4dc6498a49048ecea/core/java/android/app/ActivityThread.java#114">ActivityThread</a> proceeds by calling<a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Instrumentation.java#1271"><em>callActivityOnCreate()</em></a>. And this is the start of what we all know as <em>“ActivityLifeCycle” </em>😄</p><h4>Thanks for reading through 🙌🏼. If you found this post useful, please share it through your circles.</h4><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2IVAl0TbsfES9cFGYr40g.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_read_later_text">Journal</a>.</p><p>🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: <a href="https://usejournal.com/newsletter/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_text">Get the noteworthy newsletter &gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b64e11dc157" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>