<?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 Jasmeet Singh on Medium]]></title>
        <description><![CDATA[Stories by Jasmeet Singh on Medium]]></description>
        <link>https://medium.com/@sjasmeet438?source=rss-8b9e48d1942f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MohnM8g8Pss6_srFPXzQgA.jpeg</url>
            <title>Stories by Jasmeet Singh on Medium</title>
            <link>https://medium.com/@sjasmeet438?source=rss-8b9e48d1942f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:52:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sjasmeet438/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[An Ocean Made of Math]]></title>
            <link>https://medium.com/@sjasmeet438/an-ocean-made-of-math-e4c04ed1aa40?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c04ed1aa40</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[procedural-generation]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 06:14:44 GMT</pubDate>
            <atom:updated>2026-11-30T06:14:44.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: waves, light and a storm in one shader</h4><figure><img alt="Animated montage of a procedural ocean with a lighthouse at sunset, at night with rotating beams, in a storm with lightning, and in daylight" src="https://cdn-images-1.medium.com/max/480/1*a2QteGwgXIlzrNPrijXj4A.gif" /><figcaption>Sunset, night, storm and day: every frame computed live by one shader on an Android phone</figcaption></figure><p>This is Part 3 of the ShaderLab series. <a href="https://medium.com/p/6ed4c620a852">Part 1</a> built the cross-platform shader pipeline with a Mandelbrot explorer. <a href="https://medium.com/p/8fd9cb79c91e">Part 2</a> bent light around a black hole. This one renders an open ocean: waves, a sunset, a lighthouse that switches on at night, and a storm with rain and lightning.</p><p>There are no models, no textures and no video files. Every pixel is computed by one fragment shader, every frame, on Android, iOS and Desktop through Compose Multiplatform.</p><p>This article covers:</p><ul><li>Building waves that look like a real sea.</li><li>Ray marching a height field, and why it’s different from Part 2.</li><li>Shading water: Fresnel, sun glitter and light through the crests.</li><li>A lighthouse from three analytic shapes and a rotating beam.</li><li>Storm mode: rain, lightning and whitecaps.</li><li>The Android error “program is too large”, and how loop unrolling caused it.</li></ul><h3>The scene in four numbers</h3><p>The Kotlin side passes just four values to the shader:</p><ul><li>uLook: where the camera looks (yaw, pitch). Drag sideways to turn.</li><li>uSun: the sun&#39;s height above the horizon, in radians. Drag up and down to move it. On desktop, the scroll wheel works too.</li><li>uSea: how rough the sea is. 1.0 is calm, 1.8 is a storm.</li><li>uTime: the clock from Part 1&#39;s ShaderCanvas.</li></ul><p>The sunset, day and night presets just animate uSun to a target value. The storm button animates uSea from 1.0 to 1.8 over 1.8 seconds. Everything else (sky colour, lamp, clouds, fog) is derived from those values inside the shader.</p><h3>Waves that look like a sea</h3><p>The sea surface is a height field: for any point (x, z) on the water, a function returns the height. The classic approach is a sum of sine waves. Sines look too smooth and too symmetric, though. Real waves have sharp crests and wide, flat troughs.</p><p>A cheap fix: use exp(sin(x) - 1) instead of sin(x). It is 1 at the crest and drops off fast, so peaks get pointy and troughs flatten out. I learned this shape, and the drag trick below, from afl_ext’s <a href="https://www.shadertoy.com/view/MdXyzX">Very fast procedural ocean</a> on Shadertoy.</p><pre>for (int i = 0; i &lt; 30; i++) {<br>    if (i &gt;= iters) break;<br>    // wind-driven sea: long waves follow the wind, short ones spread wider<br>    float ang = WIND + sin(float(i) * 2.39996) * (0.45 + 0.05 * float(i));<br>    float2 d = float2(sin(ang), cos(ang));<br>    // deep water: phase speed grows with wavelength, so omega ~ sqrt(k)<br>    float x = dot(d, q) * freq + uTime * 1.6 * sqrt(freq);<br>    float w = exp(sin(x) - 1.0);<br>    float dw = w * cos(x);<br>    q -= d * dw * amp * 0.32 * uSea / freq;   // drag toward the crest<br>    sum += w * amp;<br>    grad += d * dw * freq * amp;<br>    total += amp;<br>    freq *= 1.18;<br>    amp *= 0.83;<br>}</pre><p>Each line here fixed something that looked fake in my first version:</p><ul><li><strong>Wind direction.</strong> At first the waves came from random directions and the sea looked like a choppy pond. Now every wave is centred on one wind angle. The long waves follow it closely and the short ones spread wider. 2.39996 is the golden angle in radians, which spreads the directions evenly without repeating.</li><li><strong>Deep-water speed.</strong> In deep water, long waves travel faster than short ones. Multiplying time by sqrt(freq) gives each octave the right speed, so the sea doesn&#39;t move as one rigid sheet.</li><li><strong>Drag.</strong> Each wave pushes the sample point towards its own crest, so the next waves bunch up there. That’s what makes crests look busy and troughs calm.</li><li><strong>Octaves.</strong> Each wave is 1.18× higher in frequency and 0.83× smaller than the previous one, from long swells down to small chop.</li></ul><p>The loop also accumulates the slope (grad) analytically, using the derivative of exp(sin(x) - 1), which is w * cos(x). That means the surface normal comes out of the same pass. The usual alternative is sampling the height three times to estimate it, which would triple the cost. The drag is left out of the derivative, which is an approximation you can&#39;t see.</p><h3>Ray marching a height field</h3><p>In Part 2, rays curved, so the shader took 240 small steps. Here rays are straight, but the surface is bumpy. A height field isn’t a distance field, so the usual “sphere tracing” trick of jumping by the distance to the surface doesn’t apply.</p><p>The trick is that the sea is bounded. With the formula above, the surface always lies between y = 0 (wave tops) and y = −2 · uSea (wave bottoms). So:</p><ol><li>Intersect the ray with the top plane. If that’s further than the far limit, the pixel shows sky.</li><li>Intersect it with the bottom plane. The water surface must be somewhere between the two.</li><li>Walk between them in 14 even steps until a step lands below the water.</li><li>Bisect that last step 5 times to find the surface precisely.</li></ol><pre>float t0 = tTop;<br>float t1 = tTop;<br>float stepLen = (tBot - tTop) / 14.0;<br>for (int i = 0; i &lt; 14; i++) {<br>    t1 = t0 + stepLen;<br>    float3 q = ro + rd * t1;<br>    if (q.y &lt; seaTrace(q.xz)) break;<br>    t0 = t1;<br>}<br>for (int i = 0; i &lt; 5; i++) {<br>    float tm = 0.5 * (t0 + t1);<br>    float3 q = ro + rd * tm;<br>    if (q.y &lt; seaTrace(q.xz)) t1 = tm; else t0 = tm;<br>}</pre><p>19 height lookups per pixel find the surface. Notice it calls seaTrace, not the full wave function. That&#39;s on purpose, and it&#39;s the heart of the Android story below.</p><p><strong>Level of detail.</strong> Once the hit is found, the full wave function runs once, for the normal. It uses 26 octaves up close, 18 at middle distance and 10 far away. Far waves are smaller than a pixel, and computing them anyway just makes the horizon sparkle with noise. For the same reason, normals blend towards flat with distance.</p><h3>Shading the water</h3><p>Water barely has a colour of its own. What you see is mostly reflection, and how much it reflects depends on the angle. Looking straight down, water reflects about 2% of the light. At a grazing angle, near the horizon, it reflects almost everything. That’s the Fresnel effect, and <a href="https://en.wikipedia.org/wiki/Schlick%27s_approximation">Schlick’s approximation</a> computes it in one line:</p><pre>float fres = 0.02 + 0.98 * pow(1.0 - max(dot(n, -rd), 0.0), 5.0);<br>col = mix(water, clouds(refl, sky(refl)), fres);</pre><p>This is why the sea is dark under the camera and turns into a mirror of the sky towards the horizon. No tuning needed: the physics does it.</p><p><strong>Sun glitter.</strong> The sharp highlight of the sun on the waves is a very tight specular term, pow(dot(refl, sun), 1400). My first version added it on top of everything, and in daylight it became one big white blob under the sun. Two changes fixed it:</p><ul><li>The glint is multiplied by Fresnel too, so it’s weak looking down and strong at grazing angles. That’s what real glitter does.</li><li>Small “capillary” ripples, from two noise lookups, tilt the normals up close. They break the glint into separate sparkles instead of one smooth highlight. They fade out with distance, where they’d only add noise.</li></ul><pre>float spec = pow(max(dot(refl, sun), 0.0), 1400.0) * smoothstep(-0.03, 0.02, sun.y);<br>// sun glint obeys Fresnel too: weak looking straight down, strong at grazing angles<br>col += sunColor() * (spec * 260.0 * (1.0 - stormAmount()) + sheen * 0.8) * fres;</pre><figure><img alt="Turquoise ocean in daylight with sparkling sun glints on the waves in front and a striped lighthouse on a small island at the horizon" src="https://cdn-images-1.medium.com/max/1024/1*BJEqeaxQrSk9q0pi3rOq5g.png" /><figcaption>Daylight: the sea darkens under the camera and mirrors the sky near the horizon (Fresnel), while ripples break the sun glint into sparkles</figcaption></figure><p><strong>Light through the crests.</strong> When the sun is behind a wave, light leaks through the thin crest and turns it glassy green. The shader fakes this subsurface scattering by brightening high points of the wave, more so when you look towards the sun.</p><p><strong>A boat, not a tripod.</strong> One last detail made a big difference: the camera rides the swell. Its height follows the wave under it, so the horizon bobs gently, as it would from a small boat.</p><pre>float3 ro = float3(0.0, CAM_H + seaTrace(float2(0.0, 0.0)) * 0.6, 0.0);</pre><h3>The sky does the colour grading</h3><p>All the mood comes from the sun’s height. Three helper functions turn uSun into blend factors:</p><ul><li>dayAmount(): 0 at night, 1 in full daylight.</li><li>sunsetAmount(): peaks when the sun touches the horizon. It fades out faster after sunset than before, so twilight turns blue instead of staying orange.</li><li>stormAmount(): 0 when calm, 1 in a full storm.</li></ul><p>The horizon is warm towards the sun and pink-violet away from it at dusk. The zenith goes from deep blue to near black. Clouds are four octaves of noise projected onto a plane high above the sea: violet away from the sun at dusk, glowing orange-pink near it. Since the water reflects the sky, every one of these colour changes shows up on the waves for free.</p><figure><img alt="Golden sunset over the ocean, with the sun low on the horizon, its reflection on the waves, and a lighthouse silhouette" src="https://cdn-images-1.medium.com/max/1024/1*QQO3zTlIxiMNnxmx2mW0fw.png" /><figcaption>Sunset: the sun’s height drives the sky, the clouds and, through reflection, the colour of the water</figcaption></figure><h3>A lighthouse from three shapes</h3><p>Ray marching a detailed model would be far too expensive. Instead, the lighthouse is built from shapes a ray can hit with one quadratic equation each:</p><ul><li>A flattened <strong>ellipsoid</strong> for the rocky islet.</li><li>A <strong>cylinder</strong> for the tower, with red and white bands from step(0.5, fract(p.y / 8.0)).</li><li>A shorter, thinner cylinder for the lantern glass, and a small ellipsoid for the roof.</li></ul><pre>// vertical cylinder around the lighthouse axis, clipped to [y0, y1]<br>float hitCylinder(float3 ro, float3 rd, float r, float y0, float y1) {<br>    float2 o = ro.xz - LH.xz;<br>    float2 d = rd.xz;<br>    float a = dot(d, d);<br>    float b = dot(o, d);<br>    float h = b * b - a * (dot(o, o) - r * r);<br>    if (h &lt; 0.0) return 1e9;<br>    float t = (-b - sqrt(h)) / a;<br>    float y = ro.y + rd.y * t;<br>    return (t &gt; 0.0 &amp;&amp; y &gt; y0 &amp;&amp; y &lt; y1) ? t : 1e9;<br>}</pre><p>Whichever shape is closest wins, and if it’s closer than the water, the pixel shows the lighthouse.</p><p><strong>The beam.</strong> The lamp switches on as the sun goes down: lampOn() = 1 - smoothstep(0.03, 0.15, uSun). The rotating beam is a line through the lamp, turning with time. For each camera ray, the shader computes the closest distance between the two lines, the view ray and the beam, and adds glow that falls off with that distance. The beam line extends both ways from the lamp, so you get a double beam without any extra code. The same function, fed the reflected ray, makes the lamp shimmer on the water.</p><figure><img alt="Dark blue night sea with a lighthouse sending two bright beams sideways and a shimmering reflection on the water" src="https://cdn-images-1.medium.com/max/1024/1*X5n1A1vU3zdJNiIcJp5BvQ.png" /><figcaption>Night: the lamp switches on and its double beam sweeps over the sea, reflected on the water</figcaption></figure><h3>Storm mode</h3><p>Turning on the storm only changes uSea. Everything else follows:</p><ul><li><strong>Taller waves.</strong> The height and drag scale with uSea, so the swell grows as the slider moves.</li><li><strong>Overcast.</strong> Sky, clouds, sun and glitter all fade towards slate grey. The water gets darker.</li><li><strong>Whitecaps.</strong> Foam appears on the sharpest crests. Up close the foam noise looked like smudges, so it fades in from about 8 units away.</li><li><strong>Rain.</strong> Three layers of streaks drawn in screen space, each a grid of hashed cells with a short line in some of them. Nearer layers are bigger and faster. They pan when you turn the camera, so the rain feels attached to the world.</li><li><strong>Lightning.</strong> Time is split into 2.6-second windows. A hash decides whether each window gets a strike and when. A strike is a double flicker, two sharp exponential decays, and it lights the sky, the clouds and the rain. The bolt itself is a thin line in the sky, made jagged by two octaves of noise.</li></ul><pre>float lightning() {<br>    float seg = floor(uTime / 2.6);<br>    float h = hash2(float2(seg, 7.1));<br>    if (h &lt; 0.45) return 0.0;<br>    float t = uTime - seg * 2.6 - h * 1.2;<br>    if (t &lt; 0.0) return 0.0;<br>    return (exp(-t * 9.0) + 0.7 * exp(-abs(t - 0.18) * 16.0)) * stormAmount();<br>}</pre><p>Finally, <a href="https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/">Krzysztof Narkowicz’s fit of the ACES filmic curve</a> compresses the bright sun and lightning without clipping everything to white:</p><pre>col = (col * (2.51 * col + 0.03)) / (col * (2.43 * col + 0.59) + 0.14);</pre><figure><img alt="Grey stormy sea in heavy rain with a jagged lightning bolt striking behind the lighthouse" src="https://cdn-images-1.medium.com/max/1024/1*csj7gLjmG9FGy48OZxS8Vg.png" /><figcaption>Storm mode: taller waves, rain streaks and a lightning bolt that lights up the sky and the sea</figcaption></figure><h3>“Program is too large”</h3><p>The ocean worked on Desktop and iOS first. On Android, the app crashed as soon as the screen opened:</p><blockquote><em>IllegalArgumentException: error: program is too large</em></blockquote><p>The shader wasn’t long. The problem was how Android’s AGSL compiler measures it: it sizes the program <strong>with every loop unrolled</strong>. A loop isn’t one copy of its body. It’s one copy per iteration, and loops inside loops multiply.</p><p>My first version marched with the full wave function. Roughly:</p><ul><li>20 march steps, each calling the wave function, whose loop bound was 40: 20 × 40 = 800 copies of the wave code.</li><li>5 bisection steps: another 5 × 40 = 200.</li><li>One more call for the normal: 40.</li></ul><p>That’s about 1,000 copies of the wave body before counting anything else. The fix was the seaTrace you saw above: a height-only copy of the wave function with a fixed 5-octave loop, used only for marching. The full function runs once per pixel, for the normal, with its loop capped at 30.</p><pre>// Height only, first 5 octaves of sea(); used inside the march loop, where AGSL&#39;s<br>// unrolled program size would explode with sea()&#39;s longer loop.<br>float seaTrace(float2 p) {<br>    // ... same wave maths, 5 iterations, no gradient ...<br>}</pre><p>Now it’s (14 + 5) × 5 = 95 copies for the march plus 30 for the normal. That’s about 8× smaller, and Android accepted it. It’s also much faster, because marching only needs a coarse surface: the detail goes into the normal, not the hit position.</p><p>The lesson: in AGSL, <strong>keep loop bounds tight, and never nest a long loop inside another</strong>. Desktop and iOS compiled the first version without complaint. Only Android enforces this limit, so test there early.</p><figure><img alt="Two phone screens side by side showing the ocean shader with the lighthouse at dusk on Android and at night on iOS" src="https://cdn-images-1.medium.com/max/1024/1*KoCs86t4WVheCJdDYVY1MA.png" /><figcaption>The same shader on Android (AGSL) and iOS (Skia SkSL)</figcaption></figure><h3>Keeping it smooth</h3><p>The waves move constantly, so this screen uses the same rule as the black hole. While the sea is playing or your finger is down, it renders at 35% resolution:</p><pre>val fast = playing || interacting<br>ShaderCanvas(<br>    shader = shader,<br>    animate = playing,<br>    // waves are raymarched per pixel: render fewer pixels while the sea moves<br>    renderScale = if (fast) 0.35f else 1f,<br>    // ...<br>)</pre><p>Together with the shorter march (14 steps instead of 20), that brought a mid-range Android phone to about 23 ms per frame. Water is soft and always moving, so the lower resolution is very hard to spot. Pause the sea and you get a full-resolution frame.</p><h3>What I learned</h3><ul><li><strong>Realism comes from small physical rules.</strong> Wind direction, deep-water speed and Fresnel each fixed something that looked fake.</li><li><strong>Split cheap and expensive work.</strong> A coarse function finds the surface. A detailed one shades it, once.</li><li><strong>Derive, don’t sample.</strong> Analytic gradients give normals almost for free.</li><li><strong>Drive everything from a few inputs.</strong> Four uniforms produce sunset, night, day and storm.</li><li><strong>On Android, loops count multiplied.</strong> Keep bounds tight and test on a real device early.</li></ul><h3>The series so far</h3><p>Three experiments so far, one idea: write the shader once and let Compose Multiplatform run it everywhere. A fractal taught me the pipeline, a black hole taught me ray marching, and an ocean taught me where AGSL draws the line. And there’s more coming.</p><ul><li><a href="https://medium.com/p/6ed4c620a852">Part 1: One Shader, Three Platforms (Mandelbrot)</a></li><li><a href="https://medium.com/p/8fd9cb79c91e">Part 2: A Black Hole in a Shader</a></li><li>Part 3: An Ocean Made of Math (you’re here)</li></ul><p>The code is open source. Star it, fork it, and tell me what I should render next:</p><p><a href="https://github.com/jasi381/ShaderLab">github.com/jasi381/ShaderLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c04ed1aa40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Black Hole in a Shader]]></title>
            <link>https://medium.com/@sjasmeet438/a-black-hole-in-a-shader-8fd9cb79c91e?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd9cb79c91e</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[black-holes]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 06:13:31 GMT</pubDate>
            <atom:updated>2026-11-30T06:13:31.773Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: bending light with Compose Multiplatform</h4><figure><img alt="Side-by-side animated demo of a black hole shader with a glowing accretion disk on an Android phone, an iPhone simulator and a macOS window" src="https://cdn-images-1.medium.com/max/960/1*3PdhsmTAfhNkOsY0kvVN_g.gif" /><figcaption>The same black hole shader running live on Android (AGSL), iOS and Desktop (Skia SkSL) with Compose Multiplatform</figcaption></figure><p>In <a href="https://medium.com/p/6ed4c620a852">Part 1</a> I built the ShaderLab pipeline: one GPU shader string that runs on Android, iOS and Desktop through Compose Multiplatform, plus a Mandelbrot explorer on top of it. This time the shader is much heavier. It renders a black hole in real time: light bending around it, a glowing accretion disk, and the thin bright ring you see in Interstellar.</p><p>Everything here reuses Part 1’s AppShader and ShaderCanvas. If you haven&#39;t read it, the short version is: one SkSL/AGSL string, a tiny expect/actual wrapper per platform, and a composable that feeds the shader its uniforms every frame.</p><p>This article covers:</p><ul><li>How to bend light with one line of math.</li><li>Ray marching: 240 small steps per pixel.</li><li>Finding the accretion disk, including its lensed images.</li><li>Painting the disk so it looks like the movie.</li><li>Making it run on a mid-range phone.</li></ul><h3>Why you can’t just draw a black hole</h3><p>A normal 3D renderer assumes light travels in straight lines. Near a black hole it doesn’t. Gravity bends every light ray, so the same disk can appear in several places at once. The famous “arc over the top” in Interstellar isn’t the top of the disk. It’s the <em>back</em> of the disk, whose light curved up and over the black hole before reaching the camera.</p><p>So instead of drawing shapes, the shader traces light. For every pixel it fires a ray from the camera, bends it step by step, and asks: where did this ray end up?</p><ul><li><strong>It fell into the black hole:</strong> the pixel is black.</li><li><strong>It crossed the accretion disk:</strong> the pixel takes the disk’s colour.</li><li><strong>It escaped:</strong> the pixel shows whatever star is in the direction it flew off to.</li></ul><h3>Units: everything in Schwarzschild radii</h3><p>The shader measures distance in <strong>Schwarzschild radii</strong> (rₛ), the radius of the event horizon. That makes the important numbers small and memorable:</p><ul><li><strong>r = 1:</strong> the event horizon. Nothing comes back out.</li><li><strong>r = 1.5:</strong> the photon sphere. Light can orbit here, unstably.</li><li><strong>r = 3:</strong> the innermost stable circular orbit. Matter closer than this can’t orbit and falls in, so the disk starts here.</li></ul><pre>const float R_IN = 3.0;   // inner edge of the disk<br>const float R_OUT = 10.0; // outer edge</pre><h3>Bending light with one line of math</h3><p>The physically correct way is to integrate geodesics in curved spacetime. That’s heavy for a fragment shader. There’s a much cheaper trick, which I borrowed from Riccardo Antonelli’s <a href="https://rantonels.github.io/starless/"><em>Starless</em> raytracer</a>: pretend the light ray is an ordinary particle in flat space, pulled by a made-up force.</p><blockquote><em>a = −(3/2) · h² · r⃗ / r⁵</em></blockquote><p>Here <em>h</em> is the ray’s angular momentum, |r⃗ × v⃗|, which stays constant along the path. The amazing part: with this force, the particle’s path has <em>exactly</em> the shape of a light ray around a Schwarzschild black hole. In the orbit’s plane, it gives the same orbit equation that general relativity gives for light, u″ + u = (3/2)u², with u = 1/r. No tensors needed.</p><p>In the shader, that’s two lines:</p><pre>float3 hv = cross(pos, vel);<br>float h2 = dot(hv, hv);   // computed once per ray</pre><pre>// inside the loop:<br>vel += -1.5 * h2 * pos / (r * r * r * r * r) * dt;<br>float3 next = pos + vel * dt;</pre><p>This is the line from the video: <em>one line of math, repeated hundreds of millions of times per frame</em>.</p><h3>Ray marching: 240 small steps</h3><p>Each pixel’s ray starts at the camera and takes up to 240 steps:</p><pre>for (int i = 0; i &lt; 240; i++) {<br>    float r = length(pos);<br>    minR = min(minR, r);<br>    if (r &lt; 1.0) { captured = true; break; }                    // fell in<br>    if (r &gt; uDist * 1.5 &amp;&amp; dot(pos, vel) &gt; 0.0) break;        // escaped<br>    if (alpha &gt; 0.99) break;                                    // disk is opaque</pre><pre>    float dt = clamp(uStepScale * r, 0.02, 1.0);<br>    vel += -1.5 * h2 * pos / (r * r * r * r * r) * dt;<br>    float3 next = pos + vel * dt;<br>    // ... disk test, haze ...<br>    pos = next;<br>}</pre><p>Two details make 240 steps enough:</p><ul><li><strong>The step size grows with distance.</strong> dt = uStepScale * r. Far from the hole, space is nearly flat and big steps are fine. Near the photon sphere, where rays curve hardest, steps shrink to 0.02.</li><li><strong>Rays stop early.</strong> A ray that falls in, flies away, or hits enough opaque disk exits the loop. Most pixels need far fewer than 240 steps.</li></ul><p>As in Part 1, the loop bound is a constant. AGSL and SkSL don’t allow a loop bounded by a uniform, so every exit is a break.</p><h3>Finding the disk, and its ghosts</h3><p>The disk lies flat in the y = 0 plane. A ray crosses it when y changes sign between two steps. Linear interpolation gives the crossing point:</p><pre>if (pos.y * next.y &lt; 0.0) {<br>    float k = pos.y / (pos.y - next.y);<br>    float3 hit = mix(pos, next, k);<br>    float hr = length(hit.xz);<br>    if (hr &gt; R_IN &amp;&amp; hr &lt; R_OUT) {<br>        float w = (1.0 - alpha) * diskOpacity(hr);<br>        // remember up to 3 hits, shade them after the loop<br>        alpha += w;<br>    }<br>}</pre><p>Why up to three hits? Because a bent ray can cross the disk more than once. The first crossing is the disk you’d expect. The second is the disk seen <em>under</em> or <em>over</em> the black hole, after the ray looped around it. That’s the arc. A third crossing gives a faint, thin secondary image near the shadow. Blending them front to back with (1.0 - alpha) gives correct transparency for free.</p><p>The hits are only stored inside the loop. The expensive colour function runs at most three times, after the loop ends. That keeps the loop body small, which matters on Android, as we’ll see in <a href="https://medium.com/p/e4c04ed1aa40">Part 3</a>.</p><figure><img alt="Black hole with an orange-gold banded accretion disk seen almost edge-on, with the lensed back of the disk arching over the dark shadow" src="https://cdn-images-1.medium.com/max/1024/1*pkamWMcylVg8mCA3w3hecQ.png" /><figcaption>Gargantua edge-on: the arc over the top is the back of the accretion disk, bent over the black hole by gravity</figcaption></figure><h3>Painting the disk</h3><p>The physics decides <em>where</em> the disk appears. Everything else is art direction. My first version had the physics right but looked like a cream-coloured blur, not like the movie’s Gargantua. Here’s what changed.</p><p><strong>It spins at Kepler speed.</strong> Inner orbits are faster than outer ones, ω ∝ r^(−3/2). The disk texture is rotated by that angle:</p><pre>float a = atan(hit.z, hit.x) + uTime * 3.0 * pow(r, -1.5);</pre><p><strong>Fine bands, slightly warped.</strong> Interstellar’s disk has thin concentric rings. Perfect circles look fake, so I warp them with noise:</p><pre>float wob = noise2(float2(r * 3.0, 0.0) + q * 2.0);<br>// low frequencies only: higher ones alias into moire where the disk is seen edge-on<br>float bands = 0.62 + 0.24 * sin(r * 21.0 + wob * 5.0)<br>                   + 0.14 * sin(r * 8.0 + wob * 2.0);</pre><p>My first try used finer bands. Seen edge-on, the disk squashes many rings into a few pixels, and they turned into flickering moiré stripes. Lower frequencies fixed it.</p><p><strong>Orange-gold instead of cream.</strong> The disk is hottest at the inner edge, so the colour ramps from deep orange at the outside to warm white near r = 3. The bigger fix was exposure. The disk was so bright that the tone mapping saturated it to white. Lowering the exposure brought the colour back:</p><pre>col = 1.0 - exp(-col * 1.8);                   // exposure tone map<br>col = pow(max(col, float3(0.0)), float3(0.4545)); // gamma</pre><p><strong>A thin haze.</strong> On every step, the ray picks up a little glow when it’s close to the disk plane. A tight vertical falloff, exp(-abs(pos.y) * 5.0), keeps the disk looking like a thin sheet.</p><p><strong>The photon ring.</strong> Rays that pass very close to r = 1.5 orbit the hole briefly before escaping. They form the thin bright ring hugging the shadow. The shader tracks each ray’s closest approach, minR, and adds a glow when it was near 1.5:</p><pre>float ring = (minR - 1.5) * 9.0;<br>col += exp(-ring * ring) * (1.0 - alpha) * float3(1.0, 0.78, 0.55) * 0.35;</pre><figure><img alt="Black hole seen from above, with a black circular shadow ringed by a thin bright photon ring and a wide golden banded disk" src="https://cdn-images-1.medium.com/max/1024/1*21gi6sSdnMI5C_GXroDuBQ.png" /><figcaption>From above, lensing turns the disk into a ring. The thin bright line around the shadow is the photon ring at r = 1.5</figcaption></figure><p><strong>Stars, lensed for free.</strong> A ray that escapes looks up a procedural star field in the direction it <em>ends</em> up travelling, not the direction it started. So the stars near the black hole get stretched and duplicated automatically.</p><figure><img alt="Two renders of the same black hole stacked: a hazy cream-coloured disk on top and a sharper orange-gold banded disk below" src="https://cdn-images-1.medium.com/max/1024/1*qVbKuZfqKg5v6wQYbmNsAg.png" /><figcaption>First pass (top) vs movie look (bottom): same physics, only the disk’s paint changed</figcaption></figure><h3>What it leaves out (and so does the movie)</h3><p>The real thing would look different in two ways. The side of the disk moving towards you should be much brighter and bluer than the side moving away (Doppler beaming). And light climbing out of the gravity well gets redder (gravitational redshift). The Interstellar team left those out to keep the image readable (they explain why in <a href="https://arxiv.org/abs/1502.03808">their paper on the film’s black hole</a>), and so did I. “Closer to the movie” isn’t the same as “closer to reality”.</p><h3>Framing it on a portrait phone</h3><p>The disk is wide and a phone screen is tall. With a fixed field of view, the disk overflowed the sides in portrait. So the field of view widens when the screen is narrow:</p><pre>float halfSpanX = 0.5 * uResolution.x / minDim;<br>float fov = max(1.2, 1.15 / max(halfSpanX, 0.5));</pre><p>On Kotlin’s side, the camera is just three floats: yaw, pitch and distance. Dragging orbits the camera, pinching changes the distance (6 to 40 rₛ), and the screen opens with a 4-second fly-in from 40 rₛ to 11. <strong>Cinematic</strong> mode drives the same three values with slow sine waves.</p><h3>Making it run on a phone</h3><p>The first version ran at about 10 fps on my phone. The maths is simple: a portrait phone has about 2.6 million pixels, and each one can take up to 240 steps, every frame. Even a good mobile GPU can’t keep up with that.</p><p>The fix reuses Part 1’s trick, with one twist. In the Mandelbrot explorer, the shader only moved while your fingers did. Here the disk spins constantly. So the rule is: whenever <em>anything</em> moves, render cheap.</p><pre>val fast = interacting || spin || cinematic || flying<br>val stepScale = if (fast) 0.09f else 0.05f</pre><pre>ShaderCanvas(<br>    shader = shader,<br>    animate = spin,<br>    renderScale = if (fast) 0.4f else 1f,<br>    // ...<br>)</pre><ul><li><strong>40% resolution</strong> means the GPU shades only about 16% of the pixels.</li><li><strong>Bigger steps</strong> (0.09 instead of 0.05) mean rays reach the disk or escape in fewer iterations.</li></ul><p>On a mid-range Android phone, janky frames dropped from 68% to 3%, at about 22 ms per frame. The disk is moving, so the lower resolution is hard to notice. Pause the spin and let go, and you get one sharp full-quality frame.</p><h3>What I learned</h3><ul><li><strong>Look for the cheap equivalent.</strong> A fake Newtonian force gives exactly the right light paths, without any general relativity in the shader.</li><li><strong>Adaptive steps beat more steps.</strong> Spend precision where the curvature is.</li><li><strong>Keep the loop body small.</strong> Store hits, shade them later.</li><li><strong>Physics sets the shape, art direction sets the look.</strong> Same equation, very different image.</li><li><strong>If it always moves, always render cheap.</strong></li></ul><h3>Next up</h3><p>In <a href="https://medium.com/p/e4c04ed1aa40"><strong>Part 3</strong></a>, ShaderLab renders an open ocean at sunset: wind-driven waves, Fresnel sun glitter, a lighthouse that switches on at night, and a storm with rain and lightning. It’s also where Android told me my shader was “too large”.</p><p>The code is open source:</p><p><a href="https://github.com/jasi381/ShaderLab">github.com/jasi381/ShaderLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd9cb79c91e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Shader, Three Platforms]]></title>
            <link>https://medium.com/@sjasmeet438/one-shader-three-platforms-6ed4c620a852?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed4c620a852</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 06:12:17 GMT</pubDate>
            <atom:updated>2026-11-30T06:12:17.077Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: a Mandelbrot explorer in Compose Multiplatform</h4><figure><img alt="Side-by-side animated demo of a Mandelbrot and Julia set GPU shader running on an Android phone, an iPhone simulator and a macOS desktop window" src="https://cdn-images-1.medium.com/max/960/1*hm2G-vrUj1mHyb_tlitz3g.gif" /><figcaption>The same Mandelbrot and Julia set shader running on Android (AGSL), iOS and Desktop (Skia SkSL) with Compose Multiplatform</figcaption></figure><p>I wanted to learn shaders properly. Not copy-paste-from-<a href="https://www.shadertoy.com/">Shadertoy</a> properly, but understand-every-line properly. So I started <strong>ShaderLab</strong>: a small Compose Multiplatform app where every screen is one GPU shader that you can touch, zoom and play with. The same Kotlin UI and the same shader source run on Android, iOS and Desktop.</p><p>This is the first part of a series:</p><ul><li><strong>Part 1 (this one):</strong> a Mandelbrot and Julia set explorer, plus the cross-platform shader pipeline that everything else is built on.</li><li><a href="https://medium.com/p/8fd9cb79c91e"><strong>Part 2:</strong></a> a black hole with gravitational lensing and a movie-style accretion disk.</li><li><a href="https://medium.com/p/e4c04ed1aa40"><strong>Part 3:</strong></a> an open ocean at sunset, with a lighthouse, a storm, rain and lightning.</li></ul><p>If you only read one part, read this one. Parts 2 and 3 reuse everything below.</p><h3>The Mandelbrot set in 60 seconds</h3><p>Take a point <em>c</em> on the complex plane. Start with <em>z = 0</em> and repeat:</p><blockquote><em>z = z² + c</em></blockquote><p>If <em>z</em> stays small forever, <em>c</em> is inside the set and we paint it black. If <em>z</em> runs away to infinity, <em>c</em> is outside, and <em>how fast</em> it escapes gives us a colour. That is the whole algorithm.</p><p>The interesting part: every pixel is independent. Pixel (412, 900) doesn’t care what pixel (413, 900) is doing. That is exactly the kind of work a GPU is built for, and exactly why a fragment shader is the right tool. One small function runs once per pixel, in parallel, every frame.</p><h3>One shader, three platforms</h3><p>Compose Multiplatform draws with Skia everywhere, but the shader APIs differ:</p><ul><li><strong>Android</strong> uses android.graphics.RuntimeShader, which takes <strong>AGSL</strong> (API 33+).</li><li><strong>iOS and Desktop</strong> use Skiko’s RuntimeEffect, which takes <strong>SkSL</strong>.</li></ul><p>The good news: AGSL is essentially SkSL. Same syntax, same half4 main(float2 fragCoord) entry point. So one shader string can serve all three. All I needed was a thin expect/actual wrapper:</p><pre>// commonMain<br>expect class AppShader(sksl: String) {<br>    fun setFloat(name: String, vararg values: Float)<br>    fun brush(): Brush<br>}</pre><p>On Android, it wraps RuntimeShader and falls back to a solid colour below API 33:</p><pre>// androidMain<br>actual class AppShader actual constructor(sksl: String) {<br>    private val supported = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU<br>    private val shader = if (supported) RuntimeShader(sksl) else null<br>    private val cached: Brush = shader?.let { ShaderBrush(it) } ?: SolidColor(Color(0xff1b1b2f))</pre><pre>    actual fun setFloat(name: String, vararg values: Float) {<br>        if (supported) shader?.setFloatUniform(name, values)<br>    }<br>    actual fun brush(): Brush = cached<br>}</pre><p>On iOS and Desktop (a shared skiaMain source set), it wraps a RuntimeShaderBuilder:</p><pre>// skiaMain<br>actual class AppShader actual constructor(sksl: String) {<br>    private val builder = RuntimeShaderBuilder(RuntimeEffect.makeForShader(sksl))</pre><pre>    actual fun setFloat(name: String, vararg values: Float) {<br>        when (values.size) {<br>            1 -&gt; builder.uniform(name, values[0])<br>            2 -&gt; builder.uniform(name, values[0], values[1])<br>            // ... 3 and 4<br>        }<br>    }<br>    actual fun brush(): Brush = ShaderBrush(builder.makeShader().asComposeShader())<br>}</pre><p>That’s the entire platform layer. Every experiment in ShaderLab sits on top of these few lines.</p><h3>ShaderCanvas: a clock, a layer and a brush</h3><p>The second building block is one composable that feeds the shader its resolution and time, and draws it:</p><pre>@Composable<br>fun ShaderCanvas(<br>    shader: AppShader,<br>    modifier: Modifier = Modifier,<br>    animate: Boolean = true,<br>    renderScale: Float = 1f,<br>    uniforms: AppShader.() -&gt; Unit = {}<br>) {<br>    var time by remember { mutableFloatStateOf(0f) }<br>    LaunchedEffect(animate) {<br>        if (!animate) return@LaunchedEffect<br>        var last = withFrameNanos { it }<br>        while (true) withFrameNanos { now -&gt;<br>            time += (now - last) / 1_000_000_000f<br>            last = now<br>        }<br>    }<br>    Box(modifier) {<br>        Canvas(<br>            Modifier.fillMaxSize(renderScale).graphicsLayer {<br>                compositingStrategy = CompositingStrategy.Offscreen<br>                transformOrigin = TransformOrigin(0f, 0f)<br>                scaleX = 1f / renderScale<br>                scaleY = 1f / renderScale<br>            }<br>        ) {<br>            shader.setFloat(&quot;uResolution&quot;, size.width, size.height)<br>            shader.setFloat(&quot;uTime&quot;, time)<br>            shader.uniforms()<br>            drawRect(brush = shader.brush())<br>        }<br>    }<br>}</pre><p>Three details matter here:</p><ul><li><strong>The clock only ticks when </strong><strong>animate is true.</strong> A still fractal costs nothing per frame.</li><li><strong>The offscreen layer</strong> caches the shader’s pixels. When a HUD panel slides over it, Compose recomposites the cached layer instead of re-running 600 iterations per pixel.</li><li><strong>renderScale</strong> draws into a smaller canvas and stretches it back to full size. At 0.4, the GPU shades about 16% of the pixels. This one parameter is the main performance lever in the whole app. More on that below.</li></ul><h3>The shader, line by line</h3><p>First, map a screen pixel to a point on the complex plane. I divide by the shorter side so the set never gets squashed, and flip Y because screen Y points down:</p><pre>float minDim = max(min(uResolution.x, uResolution.y), 1.0);<br>float2 p  = (fragCoord - 0.5 * uResolution) / minDim;<br>float2 pt = uCenter + float2(p.x, -p.y) * uScale;</pre><p>uCenter and uScale are the camera. Panning changes the centre, zooming shrinks the scale. The shader itself doesn&#39;t know about gestures at all.</p><p>Then the loop:</p><pre>float n = 0.0;<br>float r2 = 0.0;<br>for (int i = 0; i &lt; 1000; i++) {<br>    if (float(i) &gt;= uMaxIter) break;<br>    z = float2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + k;<br>    r2 = dot(z, z);<br>    if (r2 &gt; 256.0) break;<br>    n += 1.0;<br>}</pre><p>Two things here look odd if you come from Kotlin:</p><ul><li><strong>There is no complex number type.</strong> A float2 holds (real, imaginary), and z² is written out by hand: (x² − y², 2xy).</li><li><strong>The loop bound is a constant 1000</strong>, with a separate break on the uniform. AGSL and SkSL need loops with a constant upper bound, so you can&#39;t write i &lt; uMaxIter. The workaround is a fixed ceiling with an early exit.</li></ul><p>The escape radius is 16 (r² &gt; 256) instead of the textbook 2. A bigger radius makes the smooth-colouring formula below more accurate, and costs only a few extra iterations.</p><h3>Smooth colouring: getting rid of the bands</h3><p>If you colour by the raw iteration count <em>n</em>, you get hard bands, because <em>n</em> is an integer. The fix is a classic trick, explained in <a href="https://iquilezles.org/articles/msetsmooth/">Inigo Quilez’s article on smooth iteration counts</a>: estimate the fractional iteration where the point <em>would</em> have crossed the radius.</p><pre>float smoothN = n - log2(log2(r2)) + 4.0;<br>float t = smoothN / 64.0 + uTime * 0.04;</pre><p>The double log comes from the fact that |z| roughly squares every step, so the escape is doubly exponential. uTime * 0.04 slowly shifts the colours, which gives the &quot;flowing&quot; look in the video.</p><p>The colours come from <a href="https://iquilezles.org/articles/palettes/">Inigo Quilez’s cosine palette</a>. It uses four float3 values and no textures:</p><pre>float3 cosinePalette(float t, float3 a, float3 b, float3 c, float3 d) {<br>    return a + b * cos(6.28318 * (c * t + d));<br>}</pre><p>Changing d shifts the hue of each channel. That&#39;s how the app&#39;s four palettes are made: same function, different phase offsets.</p><figure><img alt="Seahorse Valley region of the Mandelbrot set with blue, orange and gold spiral tendrils, rendered by a GPU shader" src="https://cdn-images-1.medium.com/max/1024/1*2isaId5aL7NGgS53Bx-XXw.png" /><figcaption>Seahorse Valley in the Mandelbrot set, rendered by a GPU fragment shader at about 700x zoom</figcaption></figure><h3>A camera that feels right</h3><p>The shader is the easy part. Making zoom <em>feel</em> good took longer.</p><p><strong>Zoom where your fingers are.</strong> A naive zoom scales around the screen centre, which feels wrong. To keep the point under the pinch fixed, move the centre by the offset times the change in scale:</p><pre>fun zoomAt(focus: Offset, factor: Float, size: IntSize) {<br>    val minDim = minDimension(size)<br>    val ox =  (focus.x - size.width  / 2.0) / minDim<br>    val oy = -(focus.y - size.height / 2.0) / minDim<br>    val newScale = (scale / factor).coerceIn(minScale(size), MAX_SCALE)<br>    centerX += ox * (scale - newScale)<br>    centerY += oy * (scale - newScale)<br>    scale = newScale<br>}</pre><p><strong>Fly in log space.</strong> The app has six famous spots: Seahorse Valley, Elephant Valley, a mini Mandelbrot, and others. Tapping one flies the camera there. If you interpolate scale linearly from 3.2 to 0.0045, the first 99% of the zoom happens in the first few frames. Interpolating ln(scale) instead gives a constant <em>perceived</em> zoom speed:</p><pre>scale = exp(logS0 + (logS1 - logS0) * t)</pre><p>The centre then moves in proportion to how far the scale has travelled, so the target stays on screen during the whole dive.</p><p><strong>Detail that grows with depth.</strong> Near the edge of the set, points take longer to escape the deeper you go. A fixed iteration count looks mushy when zoomed in and wastes work when zoomed out. So the budget grows with the log of the zoom:</p><pre>val maxIter = (100.0 + 55.0 * log2((HOME_SCALE / scale).coerceAtLeast(1.0)))<br>    .coerceIn(if (julia) 200.0 else 100.0, 600.0)</pre><h3>Keeping it smooth on a phone</h3><p>600 iterations × ~2.5 million pixels is a lot of work for a phone GPU on every frame of a pinch. The trick is that you don’t need full quality <em>while your fingers are moving</em>. Your eye can’t read fine detail in motion anyway.</p><pre>// camera moving -&gt; cheap frames; settled for 150 ms -&gt; one full-res render<br>LaunchedEffect(Unit) {<br>    snapshotFlow { listOf(centerX, centerY, scale, juliaX, juliaY) }<br>        .drop(1)<br>        .collectLatest {<br>            isMoving = true<br>            delay(150)<br>            isMoving = false<br>        }<br>}</pre><p>While isMoving is true, the canvas renders at 40% resolution and iterations are capped at 250. The moment you stop, it does one crisp full-resolution render. collectLatest does the debouncing for free: every new camera value cancels the pending delay.</p><p>Together, these two changes turn a stuttery pinch into a smooth one, and they cost three lines.</p><h3>The wall: 32-bit floats</h3><p>Keep zooming and, at some point, the picture turns into blocky pixel soup. That’s not a bug. The shader works in 32-bit floats, which hold about 7 significant digits. Once neighbouring pixels are closer together than the float can tell apart, they all compute the same <em>c</em>.</p><p>Instead of showing garbage, the app clamps the zoom just before that point:</p><pre>fun minScale(size: IntSize): Double {<br>    val magnitude = maxOf(abs(centerX), abs(centerY), 0.5)<br>    return magnitude * 1.2e-7 * minDimension(size) * 2<br>}</pre><p>The limit depends on how far from the origin you are, because float precision is relative. Going past it needs double-float emulation or perturbation theory. That’s a rabbit hole for another day.</p><h3>Bonus: Julia sets with almost no code</h3><p>Here’s a nice symmetry. The Mandelbrot set fixes <em>z₀ = 0</em> and varies <em>c</em> per pixel. A Julia set does the opposite: it fixes <em>c</em> and uses the pixel as <em>z₀</em>. Same loop, swapped inputs:</p><pre>bool julia = uMode &gt; 0.5;<br>float2 z = julia ? pt : float2(0.0, 0.0);<br>float2 k = julia ? jc : pt;</pre><p>In Julia mode, dragging changes <em>c</em> instead of panning, so the fractal morphs under your finger. <strong>Orbit</strong> mode moves <em>c</em> around a circle of radius 0.7885, which stays close to the boundary of the Mandelbrot set. That’s where Julia sets are the most intricate:</p><pre>float a = uTime * 0.25;<br>jc = 0.7885 * float2(cos(a), sin(a));</pre><figure><img alt="Intricate Julia set fractal with dark spiral arms on a red and orange background, rendered by a GPU shader" src="https://cdn-images-1.medium.com/max/1024/1*tZXFKFQTyIUKuFb3VvIp7A.png" /><figcaption>A Julia set in ShaderLab: drag to change c and the fractal reshapes in real time</figcaption></figure><figure><img alt="Snowflake-like blue Julia set fractal clusters on a pale yellow background, rendered by a GPU shader" src="https://cdn-images-1.medium.com/max/1024/1*eaPbGY48-hNU9jTPUCOA7w.png" /><figcaption>Orbit mode: c travels around a circle of radius 0.7885, near the edge of the Mandelbrot set</figcaption></figure><h3>What I learned</h3><ul><li><strong>Write the shader once.</strong> AGSL and SkSL are close enough that one string plus a tiny expect/actual class covers Android, iOS and Desktop.</li><li><strong>Loops need constant bounds.</strong> Use a fixed ceiling with an early break on a uniform.</li><li><strong>Animate in the space humans perceive.</strong> For zoom, that’s log space.</li><li><strong>Render cheap while moving, sharp when still.</strong> A resolution scale and a 150 ms debounce do most of the performance work.</li><li><strong>Know your precision wall</strong>, and stop gracefully before you hit it.</li></ul><h3>Next up</h3><p>In <a href="https://medium.com/p/8fd9cb79c91e"><strong>Part 2</strong></a>, the same pipeline renders something far heavier: a black hole that bends light around itself, with an accretion disk and a movie-style colour grade. That one involves raymarching through curved space, and it’s where performance really starts to hurt.</p><p>The code is open source. Star it, fork it, break it:</p><p><a href="https://github.com/jasi381/ShaderLab">github.com/jasi381/ShaderLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed4c620a852" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI That Interviews You in Real-Time Using Voice — Here’s How]]></title>
            <link>https://medium.com/@sjasmeet438/i-built-an-ai-that-interviews-you-in-real-time-using-voice-heres-how-d9d5af653c13?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d5af653c13</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[job-interview-preparation]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 13:14:40 GMT</pubDate>
            <atom:updated>2026-03-15T13:40:41.123Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building Crux.ai for the Gemini Live Agent Challenge</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGO5ZI5V5_nPAmBTcbz75w.png" /></figure><h3>The Problem With Interview Prep</h3><p>You’ve read the books. You’ve done LeetCode. You’ve memorized STAR answers. But when you’re sitting in a real interview — voice shaking, camera on — nothing prepares you for the pressure of thinking <em>and</em> speaking <em>and</em> being evaluated simultaneously.</p><p>Flashcards don’t replicate that. ChatGPT text chats don’t either. What you need is a real conversational sparring partner that hears you, responds in real-time, and tells you exactly where you stumbled.</p><p>That’s what I built.</p><h3>Introducing Crux.ai</h3><p>Crux.ai is a live AI mock interview platform that uses Google’s Gemini 2.5 Flash Live API to conduct full-duplex voice interviews — just like a real one. You speak, the AI listens. It asks follow-up questions, challenges your answers, increases difficulty, and at the end generates a scorecard across four dimensions: Clarity, Confidence, Technical Depth, and Conciseness.</p><p>It supports four interview types:</p><ul><li>DSA (Dynamic programming, graphs, trees — with a live problem card)</li><li>System Design (Distributed systems, scalability trade-offs)</li><li>Android Developer (Jetpack Compose, architecture patterns, Kotlin)</li><li>HR Interview (Behavioural, leadership, conflict resolution)</li></ul><p>And three interviewer personalities:</p><ul><li>Friendly — hints if you’re stuck, encouraging tone</li><li>Strict — no hand-holding, precise answers only</li><li>FAANG-style — the highest bar, simulates top-tier interview pressure</li></ul><h3>Architecture: How It Actually Works</h3><p>The core challenge is this: Gemini’s Live API uses a persistent WebSocket connection with binary audio frames. Browsers can’t directly hold a long-lived, server-authenticated WebSocket to Gemini (API key would be exposed). So the architecture uses a server-side WebSocket proxy running on Google Cloud Run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNFjuZQRXeKC5C1CW5aHNw.jpeg" /><figcaption>System architecture</figcaption></figure><p>Why a custom server? Next.js 15’s App Router doesn’t support WebSocket upgrades natively. So I wrote a thin Node.js HTTP server (server.js) that:</p><ol><li>Boots the Next.js app handler</li><li>Intercepts HTTP upgrade requests at /api/ws</li><li>Manages the ws (WebSocket) library for the browser connection</li><li>Opens a Gemini Live session via @google/genai SDK and relays frames bidirectionally</li></ol><h3>The Tech Stack</h3><p>LayerTechnologyFrontendNext.js 15 (App Router), React 19, TailwindCSS, TypeScriptBackendNode.js 20, Custom HTTP + WebSocket serverAI — Live Interview@google/genai → gemini-2.5-flash-native-audio-previewAI — Scorecard@google/genai → gemini-2.5-flashStorageBrowser localStorage (history, last 50 sessions)DeploymentDocker (multi-stage) → Google Cloud RunReal-timews library for WebSocket relay</p><h3>The Hardest Part: Bridging Next.js and WebSockets</h3><p>Next.js is excellent — but it doesn’t expose the raw Node.js http.Server to attach WebSocket upgrade handlers. The solution: don&#39;t use Next.js&#39;s built-in server at all. Instead, create a custom server that wraps Next.js:</p><pre>// server.js (simplified)<br>import { createServer } from &#39;http&#39;;<br>import { WebSocketServer } from &#39;ws&#39;;<br>import next from &#39;next&#39;;const app = next({ dev });<br><br><br>const handler = app.getRequestHandler();<br>const server = createServer((req, res) =&gt; handler(req, res));<br>const wss = new WebSocketServer({ noServer: true });<br>server.on(&#39;upgrade&#39;, (req, socket, head) =&gt; {<br>  if (req.url.startsWith(&#39;/api/ws&#39;)) {<br>    wss.handleUpgrade(req, socket, head, (ws) =&gt; {<br>      wss.emit(&#39;connection&#39;, ws, req);<br>    });<br>  }<br>});<br>wss.on(&#39;connection&#39;, async (browserWs, req) =&gt; {<br>  // Parse interview type &amp; personality from query params<br>  // Open Gemini Live session<br>  // Relay audio frames bidirectionally<br>});</pre><p>This gives you a single process that handles both HTTP (Next.js pages/API routes) and WebSocket (Gemini Live relay) — deployable as one Docker container on Cloud Run.</p><h3>Gemini Live API: The Real Magic</h3><p>The Gemini 2.5 Flash native audio model is genuinely remarkable. It handles:</p><ul><li>Turn-taking — knows when the candidate stops speaking</li><li>Interruption — candidate can interrupt the AI mid-sentence</li><li>Transcription — both input and output text, in real-time</li><li>System instructions — injected once at session setup to define the interviewer persona</li></ul><p>Here’s how a session is initialized:</p><pre>const session = await ai.live.connect({<br>  model: &#39;gemini-2.5-flash-native-audio-preview-12-2025&#39;,<br>  config: {<br>    systemInstruction: buildSystemPrompt(type, personality),<br>    responseModalities: [&#39;AUDIO&#39;],<br>    inputAudioTranscription: {},<br>    outputAudioTranscription: {},<br>    speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: &#39;Puck&#39; } } },<br>  },<br>  callbacks: {<br>    onmessage: (msg) =&gt; relayToBrowser(browserWs, msg),<br>    onclose: () =&gt; browserWs.close(),<br>    onerror: (e) =&gt; console.error(e),<br>  },<br>});</pre><p>The system prompt is the interviewer’s brain. It defines:</p><ul><li>The role (strict FAANG interviewer, friendly mentor, etc.)</li><li>The domain (DSA, System Design, Android, HR)</li><li>Rules (one question at a time, follow-ups, increasing difficulty)</li><li>Constraints (voice-only, no markdown, no lists — natural speech only)</li></ul><h3>Dynamic DSA Problem Generation</h3><p>For DSA interviews, the server pre-generates a problem <em>before</em> the session starts, using gemini-2.5-flash in a separate call:</p><pre>async function generateDSAProblem(ai) {<br>  const response = await ai.models.generateContent({<br>    model: &#39;gemini-2.5-flash&#39;,<br>    contents: [{<br>      role: &#39;user&#39;,<br>      parts: [{ text: &#39;Generate a random DSA problem as JSON with fields: title, description, testCases, constraints, difficulty&#39; }]<br>    }]<br>  });<br>  return JSON.parse(stripMarkdown(response.text));<br>}</pre><p>This problem is rendered as a styled card in the UI when the session starts — just like a real coding interview where you’re staring at the problem statement while explaining your approach out loud.</p><h3>The Scoring System</h3><p>When the user ends the interview, the full transcript is sent to gemini-2.5-flash with a structured evaluation prompt:</p><pre>Evaluate this interview transcript. Score on:<br>- Clarity (0-10): How clear and structured were the answers?<br>- Confidence (0-10): Did the candidate sound confident?<br>- Technical Depth (0-10): Were answers technically sound and detailed?<br>- Conciseness (0-10): Were answers focused, not rambling?<br><br>Return JSON: { clarity, confidence, technical_depth, conciseness, suggestions[] }</pre><p>The result is displayed on an animated scorecard with circular score rings for each dimension plus 3–4 coaching suggestions.</p><h3>The UI: 2026 Neural Aesthetic</h3><p>The UI uses a dark glassmorphism theme built entirely with TailwindCSS:</p><ul><li>Color palette: Ink950 (#0A0A0F), Cyan400, Violet400, Emerald400</li><li>Neural Orb: A canvas-based animated orb that pulses when AI speaks (cyan) vs. candidate speaks (violet)</li><li>Bento grid layout on the home screen for interview type / personality selection</li><li>Real-time transcript renders character-by-character as speech is recognized</li></ul><h3>Deploying to Google Cloud Run</h3><p>The app is containerized in a multi-stage Dockerfile:</p><pre>FROM node:20-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci<br>COPY . .<br>RUN npm run build<br><br>FROM node:20-alpine AS runner<br>WORKDIR /app<br>ENV NODE_ENV=production<br>COPY --from=builder /app/.next/standalone ./<br>COPY --from=builder /app/.next/static ./.next/static<br>COPY --from=builder /app/public ./public<br>COPY --from=builder /app/server.js ./server.js<br>COPY --from=builder /app/node_modules ./node_modules<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>Deploy to Cloud Run:</p><pre># Build and push to Artifact Registry<br>gcloud builds submit --tag gcr.io/YOUR_PROJECT/crux-ai<br><br># Deploy to Cloud Run<br>gcloud run deploy crux-ai \<br>  --image gcr.io/YOUR_PROJECT/crux-ai \<br>  --platform managed \<br>  --region us-central1 \<br>  --allow-unauthenticated \<br>  --set-env-vars GEMINI_API_KEY=YOUR_KEY</pre><p>Cloud Run is ideal here — it scales to zero when idle, handles WebSocket connections (with session affinity), and the per-request billing fits perfectly for an interview app with bursty, long-lived sessions.</p><h3>What I Learned</h3><ol><li>Gemini Live API is production-ready. The latency is low enough that turn-taking feels genuinely natural, not robotic.</li><li>Server-side WebSocket proxy is the right pattern. Never expose your API key in the browser. The extra hop adds negligible latency.</li><li>Next.js + custom server works cleanly. The trick is output: &#39;standalone&#39; in next.config.js + your own http.Server — everything else just works.</li><li>System prompts are everything. The difference between a helpful mock interviewer and an annoying chatbot is almost entirely in the system instruction.</li><li>localStorage is enough for most things. Not everything needs a backend database. Interview history, scorecards, session data — all stored client-side. Zero latency, zero cost, zero ops.</li></ol><h3>Try It Yourself</h3><p>Built for the Gemini Live Agent Challenge hackathon. If you’re preparing for interviews — especially at FAANG-tier companies — give it a try.</p><p>#GeminiLiveAgentChallenge #GoogleAI #GeminiAPI #BuildWithGemini</p><p><em>Built with Google GenAI SDK, Next.js 15, and Google Cloud Run.</em></p><p><em>This article was created for the purposes of entering the </em><a href="https://geminiliveagentchallenge.devpost.com/"><em>Gemini Live Agent Challenge</em></a><em> hackathon.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d5af653c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Compose App Looked Clean. Layout Inspector Told a Different Story.]]></title>
            <link>https://medium.com/@sjasmeet438/my-compose-app-looked-clean-layout-inspector-told-a-different-story-bf31a82204cb?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf31a82204cb</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 06:41:39 GMT</pubDate>
            <atom:updated>2026-02-25T07:59:50.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIWBf0FDeNvM3zrDgYSP-g.jpeg" /></figure><p>A production audit of recomposition bugs, lambda instability, and the fixes that actually worked.</p><p>I thought my Compose code was clean.</p><p>MVVM architecture, proper state hoisting, remember everywhere it needed to be. Then I opened Layout Inspector with recomposition counts enabled — and watched my &quot;clean&quot; UI light up like a Christmas tree on every single user interaction.</p><p>This isn’t a theoretical post about how Compose <em>might</em> have performance issues. This is what I actually found when I audited a production healthcare app with real users, real data, and real consequences for jank.</p><p>Everything in this article has a working demo you can run yourself: <a href="https://github.com/jasi381/LayoutInspector">github.com/jasmeetsingh/LayoutInspector</a></p><p>Clone it, open Layout Inspector, and watch the counters move in real time.</p><h3>Setting Up the Audit (The Right Way)</h3><p>Before touching Layout Inspector, one thing matters: run on a real device, not an emulator. Emulators lie to you. Debug builds hide problems behind slower baselines.</p><p>Connect your device, then in Android Studio:</p><p>Tools → Layout Inspector</p><p>Connect to your running app, and — this is the part most people miss — click “Show Recomposition Counts” in the toolbar. Enable it. Now every composable in your tree shows a count of how many times it recomposed since you started watching.</p><h3>Adding the Compose Compiler Report</h3><p>Layout Inspector tells you <em>where</em> the problem is. The compiler report tells you <em>why</em> a composable can’t be skipped. Add this to your app/build.gradle.kts:</p><pre>// app/build.gradle.kts<br>composeCompiler {<br>    reportsDestination = layout.buildDirectory.dir(&quot;compose_reports&quot;)<br>    metricsDestination = layout.buildDirectory.dir(&quot;compose_reports&quot;)<br>}</pre><p>Build the project, then check app/build/compose_reports/. The *_composables.txt file lists every composable and whether Compose can skip it. You&#39;ll see entries like:</p><pre>restartable skippable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun GoodItemList(<br>  stable items: ImmutableList&lt;Item&gt;<br>)<br>restartable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun BadItemList(<br>  unstable items: List&lt;Item&gt;<br>)</pre><p>skippable means Compose can skip a recomposition if inputs haven&#39;t changed. Without it, Compose <em>always</em> recomposes the composable when its parent does — regardless of whether data changed.</p><p>Now start using your app normally. Scroll a list. Type in a search field. Navigate between screens. Then look at those numbers.</p><h3>What I Found: The Three Offenders</h3><h4>Offender #1: The Whole Screen Recomposing on Keyboard Input</h4><p>I had a search screen. User types a character → the entire list screen recomposed. Every card. Every row. Everything.</p><p>The cause was embarrassingly simple. Here’s the pattern:</p><pre>// ui/viewmodel/SearchViewModel.kt<br><br>// ❌ Single monolithic UI state object<br>data class SearchUiState(<br>    val searchQuery: String = &quot;&quot;,<br>    val filteredItems: List&lt;Item&gt; = sampleItems<br>)<br>class BadSearchViewModel : ViewModel() {<br>    private val _uiState = MutableStateFlow(SearchUiState())<br>    val uiState: StateFlow&lt;SearchUiState&gt; = _uiState.asStateFlow()<br>    fun onSearchQueryChanged(query: String) {<br>        _uiState.update {<br>            it.copy(<br>                searchQuery = query,<br>                filteredItems = if (query.isBlank()) sampleItems<br>                else sampleItems.filter { item -&gt;<br>                    item.name.contains(query, ignoreCase = true)<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>And the screen:</p><pre>// ui/screens/BadSearchScreen.kt<br><br>@Composable<br>fun BadSearchScreen(viewModel: BadSearchViewModel = viewModel()) {<br>    // Reading one combined state - any field change recomposes everything below<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br>    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {<br>        OutlinedTextField(<br>            value = uiState.searchQuery,<br>            onValueChange = { viewModel.onSearchQueryChanged(it) },<br>            label = { Text(&quot;Search&quot;) },<br>            modifier = Modifier.fillMaxWidth()<br>        )<br>        // ← Recomposes on EVERY keystroke because it reads from uiState,<br>        //   the same object that searchQuery belongs to<br>        ItemList(items = uiState.filteredItems)<br>    }<br>}</pre><p>The uiState is one object. When searchQuery changes, the entire uiState emits a new value. Compose sees a new uiState reference → everything that reads uiState recomposes — including ItemList, even though the filtered results haven&#39;t changed yet.</p><p>Run BadSearchScreen in the demo app. Open Layout Inspector. Type a character. Watch both the TextField and the ItemList counters climb together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BHBPYR2laoM6JqKTrUBkA.jpeg" /></figure><p>The fix is to split your ViewModel into separate, independent flows:</p><pre>// ui/viewmodel/SearchViewModel.kt<br><br>// ✅ Two separate StateFlows - independent read scopes<br>class GoodSearchViewModel : ViewModel() {<br>    private val _searchQuery = MutableStateFlow(&quot;&quot;)<br>    val searchQuery: StateFlow&lt;String&gt; = _searchQuery.asStateFlow()<br>    private val _filteredItems = MutableStateFlow&lt;List&lt;Item&gt;&gt;(sampleItems)<br>    val filteredItems: StateFlow&lt;List&lt;Item&gt;&gt; = _filteredItems.asStateFlow()<br>    fun onSearchQueryChanged(query: String) {<br>        _searchQuery.value = query<br>        _filteredItems.value = if (query.isBlank()) sampleItems<br>        else sampleItems.filter { it.name.contains(query, ignoreCase = true) }<br>    }<br>}</pre><p>And the screen:</p><pre>// ui/screens/GoodSearchScreen.kt<br><br>@Composable<br>fun GoodSearchScreen(viewModel: GoodSearchViewModel = viewModel()) {<br>    // Each flow is an independent read scope<br>    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()<br>    val filteredItems by viewModel.filteredItems.collectAsStateWithLifecycle()<br>    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {<br>        // Only this composable recomposes while the user types<br>        OutlinedTextField(<br>            value = searchQuery,<br>            onValueChange = { viewModel.onSearchQueryChanged(it) },<br>            label = { Text(&quot;Search&quot;) },<br>            modifier = Modifier.fillMaxWidth()<br>        )<br>        // Recomposes only when filteredItems emits - not on every keystroke<br>        ItemList(items = filteredItems)<br>    }<br>}</pre><p>Run GoodSearchScreen in the demo app and type again. Only the TextField counter increments. The ItemList stays at zero until the filter actually produces a different result.</p><p>After this change in production, ItemList recomposition count stayed at zero while the user typed. Only the TextField recomposed. Exactly what we want.</p><h4>Offender #2: Unstable Collection Types Killing List Performance</h4><p>This one is subtle and it burned me badly.</p><p>I had a LazyColumn of patient cards. The recomposition count on every card was incrementing every time I tapped a button elsewhere on screen — even though the list data was completely unchanged.</p><p>The root cause: List&lt;T&gt; is unstable in Compose&#39;s type system.</p><p>Compose’s skipping logic works like this:</p><ul><li>For stable types: compare old and new values with equals() → skip if equal</li><li>For unstable types: always assume the value might have changed → never skip</li></ul><p>List&lt;T&gt; is backed by ArrayList at runtime. Compose can&#39;t guarantee the list won&#39;t mutate between recompositions, so it marks it unstable. This means any composable accepting List&lt;T&gt; is permanently ineligible for skipping.</p><p>Here’s what it looks like:</p><pre>// ui/screens/BadListScreen.kt<br><br>@Composable<br>fun BadListScreen(modifier: Modifier = Modifier) {<br>    var recomposeCount by remember { mutableIntStateOf(0) }<br>    Column(modifier = modifier.fillMaxSize().padding(16.dp)) {<br>        Text(&quot;Parent recomposed: $recomposeCount×&quot;)<br>        Button(onClick = { recomposeCount++ }) { Text(&quot;Recompose Parent&quot;) }<br>        // List&lt;Item&gt; is unstable - BadItemList can never be skipped<br>        BadItemList(items = sampleItems)<br>    }<br>}<br>@Composable<br>private fun BadItemList(items: List&lt;Item&gt;) {  // ← unstable parameter<br>    LazyColumn {<br>        items(items, key = { it.id }) { item -&gt;<br>            BadItemCard(item = item)<br>        }<br>    }<br>}</pre><p>Run BadListScreen. Tap &quot;Recompose Parent&quot; a few times. Every single BadItemCard counter increments — even though sampleItems is the exact same list object.</p><p>The compiler report confirms it:</p><pre>restartable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun BadItemList(<br>  unstable items: List&lt;Item&gt;     ← not skippable<br>)</pre><p>The fix: use ImmutableList from <a href="https://github.com/Kotlin/kotlinx.collections.immutable">kotlinx-collections-immutable</a>.</p><pre>// app/build.gradle.kts<br>implementation(&quot;org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.7&quot;)</pre><pre>// ui/screens/GoodListScreen.kt<br><br>// Convert once at the call site<br>private val sampleItems: ImmutableList&lt;Item&gt; = (1..30).map {<br>    Item(id = it, name = &quot;Item $it&quot;, description = &quot;Description for item $it&quot;)<br>}.toImmutableList()<br>@Composable<br>fun GoodListScreen(modifier: Modifier = Modifier) {<br>    var recomposeCount by remember { mutableIntStateOf(0) }<br>    Column(modifier = modifier.fillMaxSize().padding(16.dp)) {<br>        Text(&quot;Parent recomposed: $recomposeCount×&quot;)<br>        Button(onClick = { recomposeCount++ }) { Text(&quot;Recompose Parent&quot;) }<br>        // ImmutableList&lt;Item&gt; is stable - GoodItemList CAN be skipped<br>        GoodItemList(items = sampleItems)<br>    }<br>}<br>@Composable<br>private fun GoodItemList(items: ImmutableList&lt;Item&gt;) {  // ← stable parameter<br>    LazyColumn {<br>        items(items, key = { it.id }) { item -&gt;<br>            GoodItemCard(item = item)<br>        }<br>    }<br>}</pre><p>The compiler report now shows:</p><pre>restartable skippable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun GoodItemList(<br>  stable items: ImmutableList&lt;Item&gt;     ← skippable!<br>)</pre><p>Run GoodListScreen. Tap &quot;Recompose Parent&quot;. The parent counter climbs but every GoodItemCard counter stays at zero — Compose skipped the entire list because its input was provably unchanged.</p><p>In production, this single change eliminated the “everything recomposes on every interaction” problem across the entire app. Smooth 60fps on mid-range devices.</p><h4>Offender #3: derivedStateOf Used Wrong (Or Not At All)</h4><p>I had a floating action button that should only appear when the user has scrolled past the first item. Here’s what the code looked like:</p><pre>// ui/screens/BadScrollScreen.kt<br><br>@Composable<br>fun BadScrollScreen(modifier: Modifier = Modifier) {<br>    val listState = rememberLazyListState()<br>    // ❌ This reads scroll state directly in the composable scope.<br>    //    firstVisibleItemIndex changes on every pixel of scroll →<br>    //    the entire composable recomposes on every scroll frame.<br>    val showFab = listState.firstVisibleItemIndex &gt; 0<br>    Box(modifier = modifier.fillMaxSize()) {<br>        LazyColumn(state = listState) { /* items */ }<br>        if (showFab) {<br>            ExtendedFloatingActionButton(onClick = { }) {<br>                Text(&quot;↑ Back to top&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>listState.firstVisibleItemIndex changes on every pixel of scroll. Every pixel triggers a recomposition of the entire composable just to evaluate a boolean that only meaningfully changes twice — when you scroll past item 0 going down, and again going back up.</p><p>Run BadScrollScreen. Scroll the list. Watch the recomposition counter climb into the hundreds mid-scroll.</p><p>This is exactly what derivedStateOf is for:</p><pre>// ui/screens/GoodScrollScreen.kt<br><br>@Composable<br>fun GoodScrollScreen(modifier: Modifier = Modifier) {<br>    val listState = rememberLazyListState()<br>    val coroutineScope = rememberCoroutineScope()<br>    // ✅ derivedStateOf reads scroll state on every frame internally,<br>    //    but only triggers a recomposition when the boolean RESULT changes.<br>    val showFab by remember {<br>        derivedStateOf { listState.firstVisibleItemIndex &gt; 0 }<br>    }<br>    Box(modifier = modifier.fillMaxSize()) {<br>        LazyColumn(state = listState) { /* items */ }<br>        if (showFab) {<br>            ExtendedFloatingActionButton(<br>                onClick = {<br>                    coroutineScope.launch { listState.animateScrollToItem(0) }<br>                }<br>            ) {<br>                Text(&quot;↑ Back to top&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>derivedStateOf still reads firstVisibleItemIndex on every scroll frame internally — that&#39;s how it knows when the result changes. But it only <em>triggers</em> a recomposition when the boolean flips. That&#39;s exactly twice per scroll session, regardless of how far the user scrolls.</p><p>Run GoodScrollScreen. Scroll the list. The recomposition counter increments exactly once when the FAB appears, and once when it disappears.</p><p>The rule: if you’re reading scroll state, animation values, or any rapidly changing state to derive a simpler value — wrap it in derivedStateOf.</p><h3>Reading the Compiler Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5QRlpNbY5ciTm9rvpJ8xQ.jpeg" /></figure><p>After adding the composeCompiler config and building the project, open app/build/compose_reports/app_debug-composables.txt. Look at each composable and check for two keywords:</p><ul><li>restartable — Compose can restart (recompose) this function when state changes</li><li>skippable — Compose can <em>skip</em> this function if its inputs haven&#39;t changed</li></ul><p>If a composable is restartable but not skippable, it will ALWAYS recompose when its parent does, regardless of whether any of its parameters changed.</p><p>The most common reasons a composable isn’t skippable:</p><ol><li>List&lt;T&gt; parameter — fix with ImmutableList&lt;T&gt; (see Demo 2)</li><li>Data class with var properties — make all properties val</li><li>Classes from external libraries — annotate a stable wrapper with @Immutable</li><li>Lambda parameters — ensure captured values are stable types</li></ol><p>Run the compiler report before shipping. It takes under a minute and tells you exactly which composables are perpetual recomposition sources.</p><h3>What Actually Moved the Needle</h3><p>After the full audit, here’s the ranking by impact:</p><p>Splitting monolithic UI state into granular flows had the highest impact. One state object driving everything is the single most common Compose performance mistake I see. It’s invisible until you open Layout Inspector.</p><p>ImmutableList for collection parameters eliminated the &quot;everything recomposes on every button tap&quot; problem. The compiler report is the fastest way to find this — look for any parameter marked unstable.</p><p>derivedStateOf for scroll-dependent UI made scroll interactions feel noticeably smoother on lower-end devices — the ones your actual users probably have. The counter difference in Layout Inspector is dramatic: hundreds of recompositions vs. two.</p><h3>The Honest Takeaway</h3><p>Jetpack Compose makes building UIs faster. It doesn’t automatically make them performant. The defaults are good enough to ship, but not good enough to handle a list of 200+ items, a search field with real-time filtering, and scroll-driven UI simultaneously — without someone actually thinking about recomposition scope.</p><p>Layout Inspector + the compiler report together give you a complete picture. Neither one alone is enough.</p><p>Clone the repo, run the demos side by side, and you’ll see immediately why these patterns matter:</p><pre>git clone https://github.com/jasmeetsingh/LayoutInspector.git</pre><p>Run the audit before your users run a one-star review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf31a82204cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI Bot That Writes and Posts to LinkedIn While I Sleep — Here’s How]]></title>
            <link>https://medium.com/@sjasmeet438/i-built-an-ai-bot-that-writes-and-posts-to-linkedin-while-i-sleep-heres-how-322ed568e4b9?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/322ed568e4b9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 10:19:06 GMT</pubDate>
            <atom:updated>2026-01-11T12:44:18.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built an AI Bot That Writes and Posts to LinkedIn While I Sleep — Here’s How</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FdcROrE3Mh-p_21FWZfiOA.png" /></figure><p><em>How I automated my LinkedIn presence using Python, Groq AI, and GitHub Actions (and why you should too)</em></p><h3>The Problem: LinkedIn Consistency is Hard</h3><p>Let’s be honest — maintaining a consistent LinkedIn presence is exhausting.</p><p>As an Android developer building healthcare apps during the day, the last thing I want to do at night is brainstorm “thought ” content. But I knew LinkedIn was crucial for:</p><ul><li>Building my professional network</li><li>Showcasing my expertise</li><li>Getting noticed by recruiters</li><li>Long-term career growth</li></ul><p>The irony? I’m a developer. <strong>If something is repetitive, I should automate it</strong>.</p><p>So I built a bot that:</p><ol><li>✅ Finds trending Android topics automatically</li><li>✅ Uses AI to generate engaging posts</li><li>✅ Posts to my LinkedIn profile</li><li>✅ Runs weekly on autopilot via GitHub Actions</li></ol><p><strong>Result:</strong> I wake up every Wednesday to a fresh LinkedIn post that I never wrote.</p><p>Let me show you how it works.</p><h3>The Architecture: How It Actually Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*wE1Fs1gr2tup6UFL5MDJvA.jpeg" /><figcaption>Flowchart of the automation</figcaption></figure><p>Simple, right? But the devil is in the details. Let me break down each component.</p><h3>Part 1: Finding Trending Topics (DuckDuckGo API)</h3><p>The first challenge: <strong>How do you know what’s trending?</strong></p><p>I tried multiple approaches:</p><ul><li>❌ Google Trends API (requires API key, rate limited)</li><li>❌ Twitter API (expensive, and it’s X now)</li><li>❌ Reddit API (too noisy, hard to filter)</li><li>✅ DuckDuckGo Search (free, no API key, instant results)</li></ul><h3>The Code</h3><pre>from duckduckgo_search import DDGS<br><br>def search_trending_topics(queries, max_results=5):<br>    &quot;&quot;&quot;Search for trending topics across multiple queries&quot;&quot;&quot;<br>    all_results = []<br>    <br>    with DDGS() as ddgs:<br>        for query in queries:<br>            try:<br>                results = list(ddgs.text(<br>                    query, <br>                    max_results=max_results,<br>                    region=&#39;wt-wt&#39;,  # Worldwide<br>                    safesearch=&#39;off&#39;,<br>                    timelimit=&#39;w&#39;  # Last week only<br>                ))<br>                all_results.extend(results)<br>            except Exception as e:<br>                print(f&quot;Search error for &#39;{query}&#39;: {e}&quot;)<br>                continue<br>    <br>    return all_results</pre><h3>What I Search For</h3><pre>SEARCH_QUERIES = [<br>    &quot;Android development trends 2025-2026&quot;,<br>    &quot;Kotlin new features latest&quot;, <br>    &quot;Jetpack Compose updates&quot;,<br>    &quot;Android Studio tips&quot;,<br>    &quot;Mobile app development best practices&quot;<br>]</pre><p><strong>Why this works:</strong></p><ul><li>timelimit=&#39;w&#39; ensures only recent content (last week)</li><li>Multiple queries cast a wider net</li><li>region=&#39;wt-wt&#39; gets global trends, not just local</li></ul><p><strong>Pro tip:</strong> Customise these queries for your niche. If you’re in React, search for “React 19 features”, “Next.js updates”, etc.</p><h3>Part 2: AI Content Generation (Groq + LLaMA 70B)</h3><p>Now comes the magic: <strong>Getting AI to write like a human</strong>.</p><p>I experimented with multiple AI providers:</p><ul><li>❌ OpenAI GPT-4 (expensive at scale)</li><li>❌ Anthropic Claude (also pricey)</li><li>❌ Google Gemini (inconsistent quality)</li><li>✅ Groq + LLaMA 70B (fast, free tier, excellent quality)</li></ul><h3>Why Groq?</h3><p>Groq’s LPU (Language Processing Unit) is <strong>insanely fast</strong>. My posts generate in under 2 seconds. Compare that to 10–15 seconds on other platforms.</p><p>Plus: Their free tier is generous (14,400 requests/day with LLaMA 70B).</p><h3>The Prompt Engineering</h3><p>This is where 90% of the magic happens. Here’s my system prompt:</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;You are a professional Android developer who writes <br>engaging LinkedIn posts. Your writing style is:<br><br>- Clear and conversational (not corporate jargon)<br>- Technical but accessible<br>- Uses real examples from production work<br>- Includes practical takeaways<br>- 3-5 sentences max (LinkedIn attention spans are short)<br>- Ends with a relevant question to drive engagement<br>- Uses 2-3 hashtags (no more!)<br><br>You specialize in:<br>- Android SDK and Kotlin<br>- Jetpack Compose<br>- Mobile architecture patterns<br>- Performance optimization<br>- Developer productivity<br><br>Never use:<br>- Emojis (except strategically, max 1-2)<br>- Buzzwords like &quot;game-changer&quot;, &quot;revolutionary&quot;<br>- Generic advice everyone already knows<br>- Anything that sounds like it was written by AI<br><br>Write as if you&#39;re sharing a quick insight with fellow developers <br>over coffee.&quot;&quot;&quot;</pre><h3>The Content Generation Code</h3><pre>from groq import Groq<br><br>def generate_post_with_ai(topics, api_key, dry_run=False):<br>    &quot;&quot;&quot;Use Groq AI to pick best topic and generate post&quot;&quot;&quot;<br>    <br>    # Format topics for the prompt<br>    topics_text = &quot;\n&quot;.join([<br>        f&quot;{i+1}. {t[&#39;title&#39;]}\n   {t[&#39;body&#39;][:150]}...&quot;<br>        for i, t in enumerate(topics[:5])<br>    ])<br>    <br>    prompt = f&quot;&quot;&quot;From these trending topics:<br><br>{topics_text}<br><br>Pick the MOST interesting one for Android developers and write a <br>LinkedIn post about it. Remember: technical but conversational, <br>3-5 sentences, end with a question.&quot;&quot;&quot;<br>    <br>    client = Groq(api_key=api_key)<br>    <br>    completion = client.chat.completions.create(<br>        model=&quot;llama-3.3-70b-versatile&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.8,  # More creative<br>        max_tokens=500<br>    )<br>    <br>    return completion.choices[0].message.content</pre><p>Key parameters:</p><ul><li>temperature=0.8 — Higher = more creative, lower = more predictable</li><li>max_tokens=500 — Keeps posts concise (LinkedIn sweet spot is 150-250 words)</li><li>System prompt defines personality/style</li></ul><h3>Part 3: Posting to LinkedIn (The API Nightmare)</h3><p>Oh boy. LinkedIn’s API is…<strong> let’s just say it’s an adventure.</strong></p><h3>The Authentication Dance</h3><p>LinkedIn uses OAuth 2.0, which requires:</p><ol><li>Creating a LinkedIn App (Developer Portal)</li><li>Getting client ID + secret</li><li>Redirecting user for authorization</li><li>Exchanging code for access token</li><li>Storing token securely</li></ol><p>I created a separate script (token_gen.py) to handle this one-time setup.</p><h3>The Posting Code</h3><pre>import requests<br><br>def post_to_linkedin(content, access_token, person_urn):<br>    &quot;&quot;&quot;Post content to LinkedIn&quot;&quot;&quot;<br>    <br>    url = &quot;https://api.linkedin.com/v2/ugcPosts&quot;<br>    <br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;X-Restli-Protocol-Version&quot;: &quot;2.0.0&quot;<br>    }<br>    <br>    post_data = {<br>        &quot;author&quot;: person_urn,<br>        &quot;lifecycleState&quot;: &quot;PUBLISHED&quot;,<br>        &quot;specificContent&quot;: {<br>            &quot;com.linkedin.ugc.ShareContent&quot;: {<br>                &quot;shareCommentary&quot;: {<br>                    &quot;text&quot;: content<br>                },<br>                &quot;shareMediaCategory&quot;: &quot;NONE&quot;<br>            }<br>        },<br>        &quot;visibility&quot;: {<br>            &quot;com.linkedin.ugc.MemberNetworkVisibility&quot;: &quot;PUBLIC&quot;<br>        }<br>    }<br>    <br>    response = requests.post(url, headers=headers, json=post_data)<br>    <br>    if response.status_code == 201:<br>        return True, &quot;Post successful!&quot;<br>    else:<br>        return False, f&quot;Error: {response.status_code} - {response.text}&quot;</pre><h3>The Gotchas I Discovered</h3><p><strong>Problem #1: Token Expiration</strong> LinkedIn access tokens expire after 60 days. Solution: Store expiry date and refresh proactively.</p><p><strong>Problem #2: Rate Limits</strong> LinkedIn allows ~100 posts/day. For weekly automation, this is fine. But test carefully.</p><p><strong>Problem #3: Person URN</strong> You need your LinkedIn person_urn (not just your profile URL). Get it via:</p><pre>https://api.linkedin.com/v2/me</pre><h3>Part 4: Automation (GitHub Actions)</h3><p>The final piece: <strong>Running this automatically every week</strong>.</p><p><strong>Why GitHub Actions?</strong></p><ul><li>✅ Free (2,000 minutes/month on free tier)</li><li>✅ Cron scheduling built-in</li><li>✅ Secure secrets management</li><li>✅ No server maintenance</li></ul><h3>The Workflow File</h3><p>Create .github/workflows/weekly-post.yml:</p><pre>name: Weekly LinkedIn Post<br><br>on:<br>  schedule:<br>    - cron: &#39;0 3 * * 3&#39;<br>  workflow_dispatch:<br><br># 👇 ADD WRITE PERMISSIONS TO GENERATE HISTORY<br>permissions:<br>  contents: write<br><br>jobs:<br>  post-to-linkedin:<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br>      - name: 📥 Checkout repository<br>        uses: actions/checkout@v4<br>      <br>      - name: 🐍 Setup Python<br>        uses: actions/setup-python@v5<br>        with:<br>          python-version: &#39;3.11&#39;<br>      <br>      - name: 📦 Install dependencies<br>        run: |<br>          pip install requests<br>      <br>      - name: 🤖 Run LinkedIn AI Poster<br>        env:<br>          GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}<br>          LINKEDIN_ACCESS_TOKEN: ${{ secrets.LINKEDIN_ACCESS_TOKEN }}<br>          LINKEDIN_PERSON_URN: ${{ secrets.LINKEDIN_PERSON_URN }}<br>        run: |<br>          python linkedin_ai_poster.py<br>      <br>      - name: 📚 Commit post history<br>        run: |<br>          git config --local user.email &quot;github-actions[bot]@users.noreply.github.com&quot;<br>          git config --local user.name &quot;github-actions[bot]&quot;<br>          git add post_history.json<br>          git diff --staged --quiet || git commit -m &quot;📝 Update post history [skip ci]&quot;<br>          git push</pre><h3>Cron Syntax Explained</h3><pre>&#39;0 3 * * 3&#39;<br> │ │ │ │ │<br> │ │ │ │ └── Day of week → 3 = Wednesday<br> │ │ │ └──── Month → any<br> │ │ └────── Day of month → any<br> │ └──────── Hour → 03 (UTC)<br> └────────── Minute → 0</pre><p>My schedule: Every Wednesday at 8:30 AM IST.</p><h3>Storing Secrets</h3><p>In your GitHub repo:</p><ol><li>Go to Settings → Secrets and variables → Actions</li><li>Add these secrets:</li></ol><ul><li>GROQ_API_KEY</li><li>LINKEDIN_ACCESS_TOKEN</li><li>LINKEDIN_PERSON_URN</li></ul><p><strong>Never commit these to your code!</strong></p><h3>The Safety Features</h3><p>I added several safeguards to avoid looking like a spam bot:</p><p><strong>1. Dry Run Mode</strong></p><p>Test without actually posting:</p><pre>python linkedin_ai_poster.py --dry-run</pre><p>This shows you:</p><ul><li>What topics were found</li><li>What post would be generated</li><li>NO actual posting</li></ul><p><strong>2. Post History Tracking</strong></p><pre>def save_post_history(post_content):<br>    &quot;&quot;&quot;Track what we&#39;ve posted to avoid duplicates&quot;&quot;&quot;<br>    history = load_history()<br>    <br>    history.append({<br>        &quot;timestamp&quot;: datetime.now().isoformat(),<br>        &quot;content&quot;: post_content[:100],  # First 100 chars<br>        &quot;hash&quot;: hashlib.md5(post_content.encode()).hexdigest()<br>    })<br>    <br>    with open(&quot;post_history.json&quot;, &quot;w&quot;) as f:<br>        json.dump(history, f, indent=2)</pre><p>This prevents posting:</p><ul><li>Duplicate content</li><li>Same topics repeatedly</li><li>Helps audit what’s been posted</li></ul><p><strong>3. Content Validation</strong></p><p>Before posting, I check:</p><ul><li>✅ Post isn’t empty</li><li>✅ Post is 50–2000 characters</li><li>✅ Post doesn’t match recent history</li><li>✅ Post contains at least one hashtag</li></ul><h3>The Results:</h3><h4>Sample Generated Posts:</h4><p><a href="https://www.linkedin.com/posts/jasmeet-singh-dev_androiddev-kotlin-jetpackcompose-activity-7414280418293846016-FHlh?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACDs6tgBf2iHy4JCQBMr85BT7z6WffrdbgQ"><strong>Post #1(Jetbrains previewing new features for ktor)</strong></a></p><p><a href="https://www.linkedin.com/posts/jasmeet-singh-dev_androiddev-kotlin-mobiledevelopment-activity-7414517413477777408-3bDt?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACDs6tgBf2iHy4JCQBMr85BT7z6WffrdbgQ"><strong>Post#2(Moving from Java to Kotlin: An Android Developer’s Perspective)</strong></a></p><p><strong>Total time invested: 0 minutes (</strong>after initial setup<strong>)</strong></p><h3>What Surprised Me</h3><ol><li><strong>AI quality is REALLY good</strong> — Most posts needed zero editing</li><li><strong>Engagement is comparable to manual posts</strong> — Sometimes even better</li><li><strong>No one realizes it’s automated</strong> — (Until now, I guess! 😄)</li></ol><h3>The Challenges I Faced</h3><h4>Challenge #1: AI Generated Generic Content</h4><p><strong>Problem: </strong>Early versions sounded too much like AI — lots of “game-changing” and “revolutionary” language.</p><p><strong>Solution:</strong> Heavily refined the system prompt with explicit “never use” lists and examples of good posts.</p><h4>Challenge #2: DuckDuckGo Rate Limiting</h4><p><strong>Problem:</strong> Occasionally got blocked for too many searches.</p><p><strong>Solution: </strong>Added exponential backoff and reduced search frequency (5 queries, not 20).</p><pre>import time<br>from random import uniform<br><br>def search_with_retry(query, max_retries=3):<br>    for attempt in range(max_retries):<br>        try:<br>            return ddgs.text(query, max_results=5)<br>        except Exception as e:<br>            if attempt &lt; max_retries - 1:<br>                wait = uniform(2, 5) * (2 ** attempt)  # Exponential backoff<br>                time.sleep(wait)<br>            else:<br>                raise</pre><h4>Challenge #3: LinkedIn Token Expiration(Upcoming)</h4><p><strong>Problem:</strong> Tokens expire every 60 days. Automation breaks silently.</p><p><strong>Solution: </strong>Added expiry tracking + email notification (via GitHub Actions) when token is &lt;7 days from expiration.</p><h3>Should You Build This?</h3><h4>✅ Build this if:</h4><ul><li>You struggle with LinkedIn consistency</li><li>You’re comfortable with Python</li><li>You have 2–3 hours for initial setup</li><li>You want to experiment with AI automation</li></ul><h4>❌ Skip this if:</h4><ul><li>You prefer fully manual, authentic posting</li><li>You’re uncomfortable with automation ethics</li><li>You don’t have time to monitor it initially</li><li>Your industry requires very personalized content</li></ul><h3>The Ethics Question</h3><p><strong>“Isn’t this inauthentic?</strong>”</p><p>I wrestled with this. Here’s my thinking:</p><p><strong>What the bot does:</strong></p><ul><li>✅ Finds relevant, real topics</li><li>✅ Generates posts in MY voice (via prompt engineering)</li><li>✅ Posts to MY profile with MY name</li></ul><p><strong>What the bot doesn’t do:</strong></p><ul><li>❌ Impersonate someone else</li><li>❌ Spam or mislead</li><li>❌ Post irrelevant content</li><li>❌ Engage with others (I still do that manually)</li></ul><p><strong>My take:</strong> It’s a tool, like a spell-checker or Grammarly. It helps me maintain presence, but I’m still responsible for the content.</p><p>I also:</p><ul><li>Review posts weekly (dry run first)</li><li>Respond to all comments personally</li><li>Occasionally edit AI suggestions</li><li>Stay transparent (this article!)</li></ul><h3>How to Build Your Own</h3><h4>Step 1: Clone the Repo</h4><pre>git clone https://github.com/jasi381/LinkedInPostGenerator.git<br>cd LinkedInPostGenerator<br>pip install -r requirements.txt</pre><h4>Step 2: Get API Keys</h4><p><strong>Groq (Free):</strong></p><ol><li>Visit <a href="https://console.groq.com/">https://console.groq.com</a></li><li>Sign up</li><li>Generate API key</li></ol><p><strong>LinkedIn:</strong></p><ol><li>Create LinkedIn App (<a href="https://developer.linkedin.com/">https://developer.linkedin.com</a>)</li><li>Get client ID + secret</li><li>Run token_gen.py for OAuth flow</li><li>Save tokens</li></ol><h4>Step 3: Test Locally</h4><pre># Dry run (no posting)<br>python linkedin_ai_poster.py --dry-run<br><br># Review the generated post<br># If it looks good, run for real:<br>python linkedin_ai_poster.py</pre><h4>Step 4: Set Up Automation</h4><ol><li>Fork the repo</li><li>Add secrets to GitHub Actions</li><li>Customize workflow schedule</li><li>Enable Actions in repo settings</li></ol><p><strong>That’s it! </strong>Your bot is live.</p><h3>The Bigger Picture</h3><p>This project taught me something important: <strong>Automation isn’t about replacing authenticity — it’s about enabling consistency</strong>.</p><p>As developers, we have skills that most professionals don’t:</p><ul><li>API integration</li><li>AI prompt engineering</li><li>CI/CD workflows</li><li>System automation</li></ul><p><strong>Why not use these skills for career growth?</strong></p><p>This LinkedIn bot:</p><ul><li>Saves me 2+ hours weekly</li><li>Maintains my professional presence</li><li>Showcases my automation skills</li><li>Generates opportunities</li></ul><p><strong>And now, it’s a portfolio piece too.</strong></p><h3>Try It Yourself</h3><p>Full code is on GitHub: <a href="https://github.com/jasi381/LinkedInPostGenerator">https://github.com/jasi381/LinkedInPostGenerator</a></p><p>What would you automate next?</p><p>I’m thinking:</p><ul><li>Cover letter generator (for job applications)</li><li>GitHub contribution tracker (auto-posts weekly stats)</li><li>Dev.to article sync (cross-platform publishing)</li></ul><p>Also on <strong>Dev.to</strong>: <a href="https://dev.to/jasmeet_singh_4c2c880bacd/i-built-an-ai-bot-that-writes-and-posts-to-linkedin-while-i-sleep-heres-how-107g">[link]</a></p><p>Drop your ideas in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322ed568e4b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture in Android: The Right Way to Integrate APIs (With a Secret Weapon)]]></title>
            <link>https://medium.com/@sjasmeet438/clean-architecture-in-android-the-right-way-to-integrate-apis-with-a-secret-weapon-a9de59db0ebf?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9de59db0ebf</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 04:01:57 GMT</pubDate>
            <atom:updated>2025-11-10T17:06:40.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>After 50+ API integrations, I learned that 90% of bugs don’t come from the API itself — they come from how we architect around it.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6GxcEqKh1khFgU_2gi0QQ.png" /></figure><h3>Introduction</h3><p>One year ago, I shipped an Android app that made me want to quit development. Every time the backend team changed an API response, our app crashed. Testing was a nightmare. Bug fixes took days because business logic was tangled with network calls. Sound familiar?</p><p>The problem wasn’t Retrofit. It wasn’t the API. It was my architecture — or lack thereof.</p><p>After rebuilding that app using Clean Architecture principles and integrating dozens of APIs since then, I’ve discovered something crucial: the architecture around your API calls matters more than the API library you choose. Today, I’m sharing the exact architecture pattern I use in production, complete with code examples and a secret debugging weapon that’s saved me countless hours.</p><p>If you’re tired of API-related bugs, fragile tests, and sleepless nights before releases, this guide is for you.</p><h3>The Problem: Why Most API Integrations Fail</h3><p>Let me show you what most Android developers do (myself included, early in my career):</p><pre>// ❌ The nightmare approach<br>class UserActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        lifecycleScope.launch {<br>            try {<br>                val response = RetrofitClient.api.getUser(userId)<br>                if (response.isSuccessful) {<br>                    nameTextView.text = response.body()?.name<br>                } else {<br>                    Toast.makeText(this, &quot;Error!&quot;, Toast.LENGTH_SHORT).show()<br>                }<br>            } catch (e: Exception) {<br>                Toast.makeText(this, &quot;Network error!&quot;, Toast.LENGTH_SHORT).show()<br>            }<br>        }<br>    }<br>}</pre><p>This code works… until it doesn’t. Here’s what’s wrong:</p><p><strong>1. Impossible to Test:</strong> How do you unit test this Activity? You can’t mock the network call without heroic effort.</p><p><strong>2. No Separation of Concerns:</strong> Business logic, network calls, and UI code are all mixed together.</p><p><strong>3. Error Handling is Primitive: </strong>Users see generic “Error!” messages. No retry mechanism. No offline support.</p><p><strong>4. Scaling is Painful:</strong> Need to show this user data in another screen? Copy-paste and pray.</p><p>The real cost? In one project, 70% of our production crashes came from poorly structured API calls. We spent more time fixing bugs than building features. That’s when I discovered Clean Architecture.</p><h3>Clean Architecture Overview: Three Layers of Sanity</h3><p>Clean Architecture, popularized by Uncle Bob, gives us a clear separation:</p><p><strong>1)Data Layer →</strong> Knows about APIs, databases, external data sources <br>2)<strong>Domain Layer →</strong> Contains business logic, use cases, and entities (no Android dependencies!) <br>3)<strong>Presentation Layer → </strong>UI, ViewModels, Android framework code</p><p><strong>The golden rule:</strong> Dependencies flow inward. The Domain layer knows nothing about Retrofit or ViewModels.</p><p>Here’s how data flows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByUAGQBqyKE6K5MLB8alwQ.png" /></figure><h3>The Foundation: API Interface with Retrofit</h3><p>Let’s build this step by step. First, our API service using JSONPlaceholder:</p><pre>// data/remote/ApiService.kt<br>interface ApiService {<br>    @GET(&quot;users/{id}&quot;)<br>    suspend fun getUser(@Path(&quot;id&quot;) userId: Int): UserDto<br><br>    @GET(&quot;users&quot;)<br>    suspend fun getUsers(): List&lt;UserDto&gt;<br><br>    @POST(&quot;users&quot;)<br>    suspend fun createUser(@Body user: CreateUserDto): UserDto<br>}</pre><p>Notice the suspend keyword—we&#39;re using Kotlin Coroutines for clean async code.</p><p><strong>Setting up Retrofit with Interceptors:</strong></p><pre>// data/remote/NetworkModule.kt<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object NetworkModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideLoggingInterceptor(): HttpLoggingInterceptor {<br>        return HttpLoggingInterceptor().apply {<br>            level = if (BuildConfig.DEBUG) {<br>                HttpLoggingInterceptor.Level.BODY<br>            } else {<br>                HttpLoggingInterceptor.Level.NONE<br>            }<br>        }<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideAuthInterceptor(): Interceptor {<br>        return Interceptor { chain -&gt;<br>            val request = chain.request().newBuilder()<br>                .addHeader(&quot;Authorization&quot;, &quot;Bearer YOUR_TOKEN&quot;)<br>                .addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                .build()<br>            chain.proceed(request)<br>        }<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideOkHttpClient(<br>        loggingInterceptor: HttpLoggingInterceptor,<br>        authInterceptor: Interceptor<br>    ): OkHttpClient {<br>        return OkHttpClient.Builder()<br>            .addInterceptor(authInterceptor)<br>            .addInterceptor(loggingInterceptor)<br>            .connectTimeout(30, TimeUnit.SECONDS)<br>            .readTimeout(30, TimeUnit.SECONDS)<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(&quot;https://jsonplaceholder.typicode.com/&quot;)<br>            .client(okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideApiService(retrofit: Retrofit): ApiService {<br>        return retrofit.create(ApiService::class.java)<br>    }<br>}</pre><p><strong>Pro tip:</strong> Use interceptors for cross-cutting concerns like authentication, logging, and error tracking. This keeps your API interface clean.</p><h3>The Repository Pattern: Your Safety Net</h3><p>This is where the magic happens. The Repository pattern abstracts data sources and provides clean error handling.</p><p><strong>First, our Result wrapper:</strong></p><pre>// domain/model/Result.kt<br>sealed class Result&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : Result&lt;T&gt;()<br>    data class Error(val exception: Throwable, val message: String? = null) : Result&lt;Nothing&gt;()<br>    object Loading : Result&lt;Nothing&gt;()<br>}</pre><p><strong>Domain Model (what our app cares about):</strong></p><pre>// domain/model/User.kt<br>data class User(<br>    val id: Int,<br>    val name: String,<br>    val email: String,<br>    val username: String<br>)</pre><p><strong>DTO (what the API sends):</strong></p><pre>// data/remote/dto/UserDto.kt<br>data class UserDto(<br>    val id: Int,<br>    val name: String,<br>    val username: String,<br>    val email: String,<br>    val address: AddressDto? = null,<br>    val phone: String? = null,<br>    val website: String? = null,<br>    val company: CompanyDto? = null<br>)<br><br>data class AddressDto(<br>    val street: String,<br>    val suite: String,<br>    val city: String,<br>    val zipcode: String<br>)<br><br>data class CompanyDto(<br>    val name: String,<br>    val catchPhrase: String,<br>    val bs: String<br>)</pre><p>Notice the DTO contains fields we might not need. This is common — APIs return everything, we extract what we need.</p><p><strong>Repository Interface (Domain Layer):</strong></p><pre>// domain/repository/UserRepository.kt<br>interface UserRepository {<br>    suspend fun getUser(userId: Int): Result&lt;User&gt;<br>    suspend fun getUsers(): Result&lt;List&lt;User&gt;&gt;<br>    suspend fun createUser(name: String, email: String, username: String): Result&lt;User&gt;<br>}</pre><p>Clean, simple, no Retrofit imports. This interface lives in the domain layer and can be tested with fakes.</p><pre>// data/repository/UserRepositoryImpl.kt<br>@Singleton<br>class UserRepositoryImpl @Inject constructor(<br>    private val apiService: ApiService,<br>    private val networkConnectivityManager: NetworkConnectivityManager<br>) : UserRepository {<br><br>    override suspend fun getUser(userId: Int): Result&lt;User&gt; {<br>        return safeApiCall {<br>            val userDto = apiService.getUser(userId)<br>            userDto.toDomain()<br>        }<br>    }<br><br>    override suspend fun getUsers(): Result&lt;List&lt;User&gt;&gt; {<br>        return safeApiCall {<br>            val usersDto = apiService.getUsers()<br>            usersDto.map { it.toDomain() }<br>        }<br>    }<br><br>    override suspend fun createUser(<br>        name: String,<br>        email: String,<br>        username: String<br>    ): Result&lt;User&gt; {<br>        return safeApiCall {<br>            val createUserDto = CreateUserDto(name, email, username)<br>            val userDto = apiService.createUser(createUserDto)<br>            userDto.toDomain()<br>        }<br>    }<br><br>    private suspend fun &lt;T&gt; safeApiCall(apiCall: suspend () -&gt; T): Result&lt;T&gt; {<br>        return withContext(Dispatchers.IO) {<br>            try {<br>                if (!networkConnectivityManager.isConnected()) {<br>                    return@withContext Result.Error(<br>                        IOException(&quot;No internet connection&quot;),<br>                        &quot;Please check your internet connection&quot;<br>                    )<br>                }<br><br>                val result = apiCall.invoke()<br>                Result.Success(result)<br>            } catch (e: HttpException) {<br>                Result.Error(<br>                    e,<br>                    when (e.code()) {<br>                        401 -&gt; &quot;Unauthorized. Please login again.&quot;<br>                        404 -&gt; &quot;Resource not found.&quot;<br>                        500 -&gt; &quot;Server error. Please try again later.&quot;<br>                        else -&gt; &quot;An error occurred: ${e.message()}&quot;<br>                    }<br>                )<br>            } catch (e: IOException) {<br>                Result.Error(e, &quot;Network error. Please check your connection.&quot;)<br>            } catch (e: Exception) {<br>                Result.Error(e, &quot;An unexpected error occurred.&quot;)<br>            }<br>        }<br>    }<br>}<br><br>// Mapper extension functions<br>private fun UserDto.toDomain(): User {<br>    return User(<br>        id = this.id,<br>        name = this.name,<br>        email = this.email,<br>        username = this.username<br>    )<br>}</pre><p>This is the heart of the architecture. The safeApiCall function:</p><ul><li>Checks network connectivity before making calls</li><li>Handles all error types (HTTP errors, network errors, unexpected errors)</li><li>Returns user-friendly error messages</li><li>Runs on IO dispatcher for optimal performance</li><li>Transforms DTOs to Domain models</li></ul><p>I cannot overstate how much this pattern has saved me. One centralized error handling function for all API calls.</p><h3>ViewModel Integration: Managing UI State</h3><p>Now let’s connect this to our UI layer using StateFlow:</p><pre>// presentation/viewmodel/UserViewModel.kt<br>@HiltViewModel<br>class UserViewModel @Inject constructor(<br>    private val userRepository: UserRepository<br>) : ViewModel() {<br><br>    private val _userState = MutableStateFlow&lt;Result&lt;User&gt;&gt;(Result.Loading)<br>    val userState: StateFlow&lt;Result&lt;User&gt;&gt; = _userState.asStateFlow()<br><br>    private val _usersState = MutableStateFlow&lt;Result&lt;List&lt;User&gt;&gt;&gt;(Result.Loading)<br>    val usersState: StateFlow&lt;Result&lt;List&lt;User&gt;&gt;&gt; = _usersState.asStateFlow()<br><br>    fun loadUser(userId: Int) {<br>        viewModelScope.launch {<br>            _userState.value = Result.Loading<br>            _userState.value = userRepository.getUser(userId)<br>        }<br>    }<br><br>    fun loadUsers() {<br>        viewModelScope.launch {<br>            _usersState.value = Result.Loading<br>            _usersState.value = userRepository.getUsers()<br>        }<br>    }<br><br>    fun createUser(name: String, email: String, username: String) {<br>        viewModelScope.launch {<br>            _userState.value = Result.Loading<br>            val result = userRepository.createUser(name, email, username)<br>            _userState.value = result<br><br>            // Refresh user list if creation was successful<br>            if (result is Result.Success) {<br>                loadUsers()<br>            }<br>        }<br>    }<br><br>    fun retry(action: () -&gt; Unit) {<br>        action()<br>    }<br>}</pre><p>Using it in a Composable (Jetpack Compose):</p><pre>// presentation/ui/UserScreen.kt<br>@Composable<br>fun UserScreen(<br>    userId: Int,<br>    viewModel: UserViewModel = hiltViewModel()<br>) {<br>    val userState by viewModel.userState.collectAsState()<br><br>    LaunchedEffect(userId) {<br>        viewModel.loadUser(userId)<br>    }<br><br>    when (val state = userState) {<br>        is Result.Loading -&gt; {<br>            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {<br>                CircularProgressIndicator()<br>            }<br>        }<br>        is Result.Success -&gt; {<br>            UserContent(user = state.data)<br>        }<br>        is Result.Error -&gt; {<br>            ErrorScreen(<br>                message = state.message ?: &quot;An error occurred&quot;,<br>                onRetry = { viewModel.retry { viewModel.loadUser(userId) } }<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>fun UserContent(user: User) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br>        Text(text = user.name, style = MaterialTheme.typography.headlineMedium)<br>        Spacer(modifier = Modifier.height(8.dp))<br>        Text(text = user.email, style = MaterialTheme.typography.bodyLarge)<br>        Spacer(modifier = Modifier.height(4.dp))<br>        Text(text = &quot;@${user.username}&quot;, style = MaterialTheme.typography.bodyMedium)<br>    }<br>}</pre><p>Notice how clean this is. The UI only cares about states. No try-catch blocks. No network logic. Beautiful.</p><h3>Testing Strategy: Why This Architecture Shines</h3><p>Here’s where you’ll fall in love with this architecture. Testing is effortless.</p><p><strong>Testing the Repository:</strong></p><pre>// data/repository/UserRepositoryImplTest.kt<br>class UserRepositoryImplTest {<br><br>    private lateinit var repository: UserRepositoryImpl<br>    private val mockApiService: ApiService = mockk()<br>    private val mockNetworkManager: NetworkConnectivityManager = mockk()<br><br>    @Before<br>    fun setup() {<br>        repository = UserRepositoryImpl(mockApiService, mockNetworkManager)<br>    }<br><br>    @Test<br>    fun `getUser returns success when api call succeeds`() = runTest {<br>        // Given<br>        val userId = 1<br>        val userDto = UserDto(1, &quot;John Doe&quot;, &quot;johndoe&quot;, &quot;john@example.com&quot;)<br>        coEvery { mockNetworkManager.isConnected() } returns true<br>        coEvery { mockApiService.getUser(userId) } returns userDto<br><br>        // When<br>        val result = repository.getUser(userId)<br><br>        // Then<br>        assertTrue(result is Result.Success)<br>        assertEquals(&quot;John Doe&quot;, (result as Result.Success).data.name)<br>    }<br><br>    @Test<br>    fun `getUser returns error when network is unavailable`() = runTest {<br>        // Given<br>        coEvery { mockNetworkManager.isConnected() } returns false<br><br>        // When<br>        val result = repository.getUser(1)<br><br>        // Then<br>        assertTrue(result is Result.Error)<br>        assertEquals(&quot;Please check your internet connection&quot;, (result as Result.Error).message)<br>    }<br><br>    @Test<br>    fun `getUser returns error when api returns 404`() = runTest {<br>        // Given<br>        val userId = 999<br>        coEvery { mockNetworkManager.isConnected() } returns true<br>        coEvery { mockApiService.getUser(userId) } throws HttpException(<br>            Response.error&lt;UserDto&gt;(404, &quot;&quot;.toResponseBody())<br>        )<br><br>        // When<br>        val result = repository.getUser(userId)<br><br>        // Then<br>        assertTrue(result is Result.Error)<br>        assertEquals(&quot;Resource not found.&quot;, (result as Result.Error).message)<br>    }<br>}</pre><p><strong>Testing the ViewModel:</strong></p><pre>// presentation/viewmodel/UserViewModelTest.kt<br>class UserViewModelTest {<br><br>    @get:Rule<br>    val instantExecutorRule = InstantTaskExecutorRule()<br><br>    @get:Rule<br>    val mainDispatcherRule = MainDispatcherRule()<br><br>    private lateinit var viewModel: UserViewModel<br>    private val mockRepository: UserRepository = mockk()<br><br>    @Before<br>    fun setup() {<br>        viewModel = UserViewModel(mockRepository)<br>    }<br><br>    @Test<br>    fun `loadUser updates state to Success when repository returns success`() = runTest {<br>        // Given<br>        val user = User(1, &quot;John Doe&quot;, &quot;john@example.com&quot;, &quot;johndoe&quot;)<br>        coEvery { mockRepository.getUser(1) } returns Result.Success(user)<br><br>        // When<br>        viewModel.loadUser(1)<br>        advanceUntilIdle()<br><br>        // Then<br>        val state = viewModel.userState.value<br>        assertTrue(state is Result.Success)<br>        assertEquals(&quot;John Doe&quot;, (state as Result.Success).data.name)<br>    }<br><br>    @Test<br>    fun `loadUser updates state to Error when repository returns error`() = runTest {<br>        // Given<br>        val error = Result.Error(IOException(), &quot;Network error&quot;)<br>        coEvery { mockRepository.getUser(1) } returns error<br><br>        // When<br>        viewModel.loadUser(1)<br>        advanceUntilIdle()<br><br>        // Then<br>        val state = viewModel.userState.value<br>        assertTrue(state is Result.Error)<br>        assertEquals(&quot;Network error&quot;, (state as Result.Error).message)<br>    }<br>}</pre><p>These tests run in milliseconds because there’s no Android framework involved. No emulator. No waiting.</p><h3>Error Handling: The Devil’s in the Details</h3><p>Beyond the safeApiCall function, here are additional error handling strategies I use:</p><p><strong>Network Connectivity Check:</strong></p><pre>// data/network/NetworkConnectivityManager.kt<br>@Singleton<br>class NetworkConnectivityManager @Inject constructor(<br>    @ApplicationContext private val context: Context<br>) {<br>    fun isConnected(): Boolean {<br>        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE)<br>            as ConnectivityManager<br><br>        val network = connectivityManager.activeNetwork ?: return false<br>        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false<br><br>        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)<br>    }<br>}</pre><p><strong>Retry Mechanism with Exponential Backoff:</strong></p><pre>// data/repository/RetryStrategy.kt<br>suspend fun &lt;T&gt; retryWithExponentialBackoff(<br>    times: Int = 3,<br>    initialDelay: Long = 1000,<br>    factor: Double = 2.0,<br>    block: suspend () -&gt; T<br>): T {<br>    var currentDelay = initialDelay<br>    repeat(times - 1) { attempt -&gt;<br>        try {<br>            return block()<br>        } catch (e: IOException) {<br>            // Only retry on network errors<br>            delay(currentDelay)<br>            currentDelay = (currentDelay * factor).toLong()<br>        }<br>    }<br>    return block() // Last attempt<br>}<br><br>// Usage in repository<br>override suspend fun getUser(userId: Int): Result&lt;User&gt; {<br>    return safeApiCall {<br>        retryWithExponentialBackoff {<br>            val userDto = apiService.getUser(userId)<br>            userDto.toDomain()<br>        }<br>    }<br>}</pre><p>This has reduced transient network failures by 60% in the production apps.</p><h3>Real Results: The Numbers Don’t Lie</h3><p>After implementing this architecture across 5 production apps:</p><p><strong>Before Clean Architecture:</strong></p><ul><li>70% of crashes related to API calls</li><li>Average 4–5 days to add new API endpoint</li><li>Test coverage: 12%</li><li>Time spent debugging API issues: ~40% of development time</li></ul><p><strong>After Clean Architecture:</strong></p><ul><li>8% of crashes related to API calls (90% reduction!)</li><li>Average 2–3 hours to add new API endpoint</li><li>Test coverage: 78%</li><li>Time spent debugging API issues: ~5% of development time</li></ul><p><strong>Developer experience improvements:</strong></p><ul><li>New team members productive in 2 days instead of 2 weeks</li><li>Backend API changes no longer break builds</li><li>Sleep better at night</li></ul><h3>BONUS: The Secret Weapon — Chucker</h3><p>Here’s the tool I wish I’d discovered years earlier: <a href="https://github.com/ChuckerTeam/chucker">Chucker.</a></p><p>Chucker is an in-app HTTP inspector for Android. Think of it as Chrome DevTools Network tab, but <strong>inside your Android app</strong>. No Charles Proxy. No Wireshark. No switching windows.</p><p><strong>Why Chucker is game-changing:</strong></p><ol><li><strong>Real-time debugging on device</strong>: See every API request/response as it happens</li><li><strong>No proxy setup:</strong> Works immediately, even on physical devices</li><li><strong>Detailed insights:</strong> Request/response bodies, headers, timing, size</li><li><strong>Share with team:</strong> Export requests to share with backend developers</li><li><strong>Works with HTTPS:</strong> No certificate pinning issues</li></ol><p><strong>Setup (ridiculously easy):</strong></p><pre>// build.gradle.kts (app level)<br>dependencies {<br>    debugImplementation(&quot;com.github.chuckerteam.chucker:library:4.0.0&quot;)<br>    releaseImplementation(&quot;com.github.chuckerteam.chucker:library-no-op:4.0.0&quot;)<br>}</pre><p><strong>Add to your OkHttp client:</strong></p><pre>@Provides<br>@Singleton<br>fun provideChuckerInterceptor(@ApplicationContext context: Context): ChuckerInterceptor {<br>    return ChuckerInterceptor.Builder(context)<br>        .collector(ChuckerCollector(context))<br>        .maxContentLength(250_000L)<br>        .redactHeaders(&quot;Authorization&quot;, &quot;Bearer&quot;)<br>        .alwaysReadResponseBody(true)<br>        .build()<br>}<br><br>@Provides<br>@Singleton<br>fun provideOkHttpClient(<br>    loggingInterceptor: HttpLoggingInterceptor,<br>    authInterceptor: Interceptor,<br>    chuckerInterceptor: ChuckerInterceptor<br>): OkHttpClient {<br>    return OkHttpClient.Builder()<br>        .addInterceptor(authInterceptor)<br>        .addInterceptor(chuckerInterceptor) // Add this<br>        .addInterceptor(loggingInterceptor)<br>        .connectTimeout(30, TimeUnit.SECONDS)<br>        .readTimeout(30, TimeUnit.SECONDS)<br>        .build()<br>}</pre><p>Launch Chucker from your app:</p><pre>// Add this anywhere (I put it in debug drawer)<br>val intent = Chucker.getLaunchIntent(context)<br>context.startActivity(intent)</pre><p>Or hold the app icon and you will click on Chucker shortcut</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avvezErhQTSik-4rHE6-UA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bn46YF4t4mAB0TMO3AgEpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njjm3qUpA0h4-Zx3F_nemA.png" /></figure><p><strong>Real story:</strong> Last month, our backend team swore the API was returning correct data. Using Chucker, I showed them in 30 seconds that the userId field was null in the response. Issue resolved in 5 minutes instead of hours of back-and-forth.</p><p>The library-no-op variant ensures zero overhead in release builds. It&#39;s literally free debugging power.</p><h3>Conclusion: Build APIs the Right Way</h3><p>Clean Architecture isn’t just academic theory — it’s a practical approach that will save you countless hours and headaches.</p><p><strong>Key takeaways:</strong></p><ol><li><strong>Separate concerns:</strong> Data, Domain, and Presentation layers each have clear responsibilities</li><li><strong>Centralize error handling:</strong> One safeApiCall function handles all edge cases</li><li><strong>Use sealed classes:</strong> Result wrapper forces exhaustive state handling</li><li><strong>Map DTOs to Domain models:</strong> Protect your app from API changes</li><li><strong>Embrace testability:</strong> Write fast unit tests without emulators</li><li><strong>Add Chucker:</strong> Your new best friend for API debugging</li></ol><p>Start with one API endpoint. Implement this architecture. Feel the difference. Then refactor the rest.</p><p>Your future self (and your team) will thank you.</p><p><strong>Ready to level up your Android architecture?</strong> Try this pattern in your next feature and share your experience in the comments. What challenges are you facing with API integration?</p><h3>Appendix: Error Handling Flow</h3><p>Here’s how errors are handled throughout the architecture:</p><pre>API Call (in PostRepositoryImpl)<br>    │<br>    ├─▶ SUCCESS<br>    │   └─▶ PostDto received<br>    │       └─▶ toDomain() mapping<br>    │           └─▶ Result.Success(Post)<br>    │               └─▶ ViewModel receives success<br>    │                   └─▶ PostsUiState.Success<br>    │                       └─▶ UI shows posts<br>    │<br>    ├─▶ IOException (Network Error)<br>    │   └─▶ Caught in safeApiCall<br>    │       └─▶ Result.Error(&quot;Network error. Check your connection.&quot;)<br>    │           └─▶ ViewModel receives error<br>    │               └─▶ PostsUiState.Error<br>    │                   └─▶ UI shows error with retry button<br>    │<br>    ├─▶ HttpException (HTTP Error)<br>    │   └─▶ Caught in safeApiCall<br>    │       └─▶ Error message based on code:<br>    │           • 400 → &quot;Bad request&quot;<br>    │           • 401 → &quot;Unauthorized&quot;<br>    │           • 404 → &quot;Not found&quot;<br>    │           • 500 → &quot;Server error&quot;<br>    │           └─▶ Result.Error(message)<br>    │               └─▶ ViewModel receives error<br>    │                   └─▶ PostsUiState.Error<br>    │                       └─▶ UI shows error with retry<br>    │<br>    └─▶ Other Exception<br>        └─▶ Caught in safeApiCall<br>            └─▶ Result.Error(&quot;Unexpected error: ${e.localizedMessage}&quot;)<br>                └─▶ ViewModel receives error<br>                    └─▶ PostsUiState.Error<br>                        └─▶ UI shows error with retry</pre><p><strong>📦 Complete Code: </strong><a href="https://github.com/jasi381/Network">Github Repo</a></p><p>🔗 <strong>Connect with me: </strong><a href="https://www.linkedin.com/in/jasmeet-singh-dev/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9de59db0ebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Ready Real-Time Chat System with Socket.IO in Android]]></title>
            <link>https://medium.com/@sjasmeet438/building-a-production-ready-real-time-chat-system-with-socket-io-in-android-cf98428da615?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf98428da615</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 03:01:54 GMT</pubDate>
            <atom:updated>2025-11-04T03:01:54.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>From prototype to 99.5% uptime: Lessons learned scaling real-time messaging to 50+ concurrent users</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V60KSZbBIz0MdmZ_1IaAag.png" /></figure><h3>Introduction</h3><p>“Building chat that handles 50+ concurrent users with 99.5% uptime taught me architecture matters more than technology.”</p><p>When I first built a real-time chat feature for an Android app, I thought it would be straightforward — just connect to a server, send messages, receive messages. Simple, right? Wrong. The moment the feature went to production, reality hit hard: network interruptions, battery drain complaints, messages disappearing into the void, and state management nightmares.</p><p>After months of iterations, refactoring, and production monitoring, I learned that building real-time chat isn’t about choosing the right library — it’s about designing a resilient architecture that handles the chaos of mobile networks. In this article, I’ll share the architectural patterns, implementation strategies, and hard-won lessons from building a chat system that now serves 50+ concurrent users with 99.5% uptime and sub-200ms message latency.</p><p>Whether you’re building your first chat feature or scaling an existing one, this guide will walk you through the critical decisions and practical code patterns that separate a demo from production-ready software.</p><h3>REST vs WebSocket: Choosing the Right Protocol</h3><p>Before diving into Socket.IO, let’s address the elephant in the room: when should you use WebSocket connections versus traditional REST APIs?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSxRDpWGXO8CWuUGFFaBZg.png" /></figure><p>REST API is ideal when:</p><ul><li>You need request-response patterns with clear boundaries</li><li>Data updates are infrequent (every few minutes or longer)</li><li>You’re building features like profile updates, settings changes, or file uploads</li><li>You want simpler server infrastructure and easier debugging</li></ul><p>WebSocket (Socket.IO) excels when:</p><ul><li>You need true real-time bidirectional communication</li><li>Server needs to push updates without client polling</li><li>You’re building chat, live feeds, collaborative editing, or gaming features</li><li>You want to minimize network overhead and battery drain</li></ul><p>For chat systems, WebSocket is non-negotiable. Polling a REST endpoint every few seconds creates unnecessary battery drain, server load, and introduces latency. Socket.IO specifically adds valuable features over raw WebSockets: automatic reconnection, event-based messaging, room support, and fallback to HTTP long-polling when WebSockets aren’t available.</p><p>The hybrid approach I recommend: Use WebSocket for real-time message exchange, but REST for heavy operations like media uploads, user profile management, and initial data synchronization. This separation of concerns keeps your WebSocket connection lightweight and focused on what it does best — instant message delivery.</p><h3>Socket.IO Integration: Setting Up the Foundation</h3><p>Let’s start with the practical implementation. First, add the necessary dependencies to your build.gradle.kts:</p><pre>dependencies {<br>    // Socket.IO client<br>    implementation(&quot;io.socket:socket.io-client:2.1.1&quot;)<br><br>    // WorkManager for background tasks<br>    implementation(&quot;androidx.work:work-runtime-ktx:2.11.0&quot;)<br>}</pre><p>Now, let’s build a robust SocketManager that handles the complexity of Socket.IO lifecycle management:</p><pre>class SocketManager private constructor(private val context: Context) {<br>    private var socket: Socket? = null<br>    private val _connectionState = MutableStateFlow&lt;ConnectionState&gt;(ConnectionState.Disconnected)<br>    val connectionState: StateFlow&lt;ConnectionState&gt; = _connectionState.asStateFlow()<br><br>    private val reconnectAttempts = AtomicInteger(0)<br>    private val maxReconnectAttempts = 5<br><br>    companion object {<br>        @Volatile<br>        private var instance: SocketManager? = null<br><br>        fun getInstance(context: Context): SocketManager {<br>            return instance ?: synchronized(this) {<br>                instance ?: SocketManager(context.applicationContext).also { instance = it }<br>            }<br>        }<br>    }<br><br>    fun connect(authToken: String) {<br>        if (socket?.connected() == true) {<br>            Log.d(&quot;SocketManager&quot;, &quot;Already connected&quot;)<br>            return<br>        }<br><br>        try {<br>            val options = IO.Options().apply {<br>                auth = mapOf(&quot;token&quot; to authToken)<br>                reconnection = true<br>                reconnectionDelay = 1000<br>                reconnectionDelayMax = 5000<br>                reconnectionAttempts = maxReconnectAttempts<br>                timeout = 10000<br>            }<br><br>            socket = IO.socket(&quot;https://your-server.com&quot;, options).apply {<br>                setupEventListeners()<br>                connect()<br>            }<br><br>            _connectionState.value = ConnectionState.Connecting<br>        } catch (e: Exception) {<br>            Log.e(&quot;SocketManager&quot;, &quot;Connection failed&quot;, e)<br>            _connectionState.value = ConnectionState.Error(e.message ?: &quot;Unknown error&quot;)<br>        }<br>    }<br><br>    private fun Socket.setupEventListeners() {<br>        on(Socket.EVENT_CONNECT) {<br>            Log.d(&quot;SocketManager&quot;, &quot;Connected to server&quot;)<br>            _connectionState.value = ConnectionState.Connected<br>            reconnectAttempts.set(0)<br>        }<br><br>        on(Socket.EVENT_DISCONNECT) { args -&gt;<br>            Log.d(&quot;SocketManager&quot;, &quot;Disconnected: ${args.firstOrNull()}&quot;)<br>            _connectionState.value = ConnectionState.Disconnected<br>        }<br><br>        on(Socket.EVENT_CONNECT_ERROR) { args -&gt;<br>            val error = args.firstOrNull()?.toString() ?: &quot;Connection error&quot;<br>            Log.e(&quot;SocketManager&quot;, &quot;Connection error: $error&quot;)<br>            _connectionState.value = ConnectionState.Error(error)<br>        }<br>    }<br><br>    fun emit(event: String, vararg args: Any) {<br>        socket?.emit(event, *args) ?: run {<br>            Log.w(&quot;SocketManager&quot;, &quot;Cannot emit &#39;$event&#39;: socket not connected&quot;)<br>        }<br>    }<br><br>    fun on(event: String, listener: Emitter.Listener) {<br>        socket?.on(event, listener)<br>    }<br><br>    fun disconnect() {<br>        socket?.disconnect()<br>        socket?.off()<br>        _connectionState.value = ConnectionState.Disconnected<br>    }<br>}<br><br>sealed class ConnectionState {<br>    object Connecting : ConnectionState()<br>    object Connected : ConnectionState()<br>    object Disconnected : ConnectionState()<br>    data class Error(val message: String) : ConnectionState()<br>}</pre><p>This SocketManager provides a clean, lifecycle-aware interface to Socket.IO with built-in state management using Kotlin Flow. The singleton pattern ensures a single connection throughout your app&#39;s lifecycle.</p><h3>State Management: Building a Resilient Repository Layer</h3><p>The repository pattern is crucial for managing chat state and decoupling your UI from network operations. Here’s a production-ready ChatRepository:</p><pre>class ChatRepository(<br>    private val socketManager: SocketManager,<br>    private val messageDao: MessageDao,<br>    private val offlineQueue: OfflineMessageQueue<br>) {<br>    private val _messages = MutableStateFlow&lt;List&lt;Message&gt;&gt;(emptyList())<br>    val messages: StateFlow&lt;List&lt;Message&gt;&gt; = _messages.asStateFlow()<br><br>    private val _connectionState = socketManager.connectionState<br>    val connectionState: StateFlow&lt;ConnectionState&gt; = _connectionState<br><br>    init {<br>        setupSocketListeners()<br>        loadCachedMessages()<br>        observeConnectionState()<br>    }<br><br>    private fun setupSocketListeners() {<br>        // Listen for incoming messages<br>        socketManager.on(&quot;message:new&quot;) { args -&gt;<br>            val messageJson = args.firstOrNull() as? JSONObject ?: return@on<br>            val message = parseMessage(messageJson)<br><br>            CoroutineScope(Dispatchers.IO).launch {<br>                // Save to local database<br>                messageDao.insert(message)<br><br>                // Update UI state<br>                val updatedMessages = _messages.value.toMutableList().apply {<br>                    add(message)<br>                    sortByDescending { it.timestamp }<br>                }<br>                _messages.value = updatedMessages<br>            }<br>        }<br><br>        // Listen for message delivery confirmations<br>        socketManager.on(&quot;message:delivered&quot;) { args -&gt;<br>            val messageId = args.firstOrNull() as? String ?: return@on<br>            updateMessageStatus(messageId, MessageStatus.DELIVERED)<br>        }<br><br>        // Listen for read receipts<br>        socketManager.on(&quot;message:read&quot;) { args -&gt;<br>            val messageId = args.firstOrNull() as? String ?: return@on<br>            updateMessageStatus(messageId, MessageStatus.READ)<br>        }<br>    }<br><br>    private fun loadCachedMessages() {<br>        CoroutineScope(Dispatchers.IO).launch {<br>            val cachedMessages = messageDao.getAllMessages()<br>            _messages.value = cachedMessages<br>        }<br>    }<br><br>    private fun observeConnectionState() {<br>        CoroutineScope(Dispatchers.IO).launch {<br>            _connectionState.collect { state -&gt;<br>                when (state) {<br>                    is ConnectionState.Connected -&gt; {<br>                        // Process offline queue when connection is restored<br>                        offlineQueue.processQueue()<br>                    }<br>                    is ConnectionState.Disconnected,<br>                    is ConnectionState.Error -&gt; {<br>                        // Mark all pending messages as queued<br>                        updatePendingMessagesStatus()<br>                    }<br>                    else -&gt; { /* No action needed */ }<br>                }<br>            }<br>        }<br>    }<br><br>    suspend fun sendMessage(content: String, recipientId: String): Result&lt;Message&gt; {<br>        val message = Message(<br>            id = UUID.randomUUID().toString(),<br>            content = content,<br>            senderId = getCurrentUserId(),<br>            recipientId = recipientId,<br>            timestamp = System.currentTimeMillis(),<br>            status = MessageStatus.PENDING<br>        )<br><br>        // Optimistic update: show message immediately in UI<br>        val updatedMessages = _messages.value.toMutableList().apply {<br>            add(message)<br>        }<br>        _messages.value = updatedMessages<br><br>        // Save to local database<br>        messageDao.insert(message)<br><br>        return when (_connectionState.value) {<br>            is ConnectionState.Connected -&gt; {<br>                // Send through socket<br>                socketManager.emit(&quot;message:send&quot;, message.toJson())<br>                Result.success(message)<br>            }<br>            else -&gt; {<br>                // Add to offline queue<br>                offlineQueue.enqueue(message)<br>                updateMessageStatus(message.id, MessageStatus.QUEUED)<br>                Result.failure(Exception(&quot;Offline - message queued&quot;))<br>            }<br>        }<br>    }<br><br>    private fun updateMessageStatus(messageId: String, status: MessageStatus) {<br>        CoroutineScope(Dispatchers.IO).launch {<br>            messageDao.updateStatus(messageId, status)<br><br>            val updatedMessages = _messages.value.map { message -&gt;<br>                if (message.id == messageId) message.copy(status = status)<br>                else message<br>            }<br>            _messages.value = updatedMessages<br>        }<br>    }<br>}<br><br>enum class MessageStatus {<br>    PENDING, QUEUED, SENT, DELIVERED, READ, FAILED<br>}</pre><p>Key architectural decisions:</p><ol><li><strong>Kotlin Flow for reactive updates:</strong> UI components observe StateFlow, ensuring automatic updates when messages arrive or connection state changes.</li><li><strong>Optimistic updates: </strong>Messages appear in the UI immediately, then sync in the background. This creates a responsive user experience even on slow networks.</li><li><strong>Local persistence:</strong> Using Room database ensures messages persist across app restarts and provides instant load times.</li><li><strong>Clear separation of concerns:</strong> The repository handles business logic; SocketManagerhandles networking; UI components simply observe state.</li></ol><h3>Offline Queue: Never Lose a Message</h3><p>Mobile networks are unreliable. Your chat system must gracefully handle offline scenarios. Here’s an OfflineMessageQueue implementation using WorkManager:</p><pre>class OfflineMessageQueue(<br>    private val context: Context,<br>    private val messageDao: MessageDao,<br>    private val socketManager: SocketManager<br>) {<br>    private val queuedMessages = ConcurrentLinkedQueue&lt;Message&gt;()<br><br>    suspend fun enqueue(message: Message) {<br>        queuedMessages.offer(message)<br>        messageDao.insert(message.copy(status = MessageStatus.QUEUED))<br><br>        // Schedule background sync<br>        scheduleSync()<br>    }<br><br>    suspend fun processQueue() {<br>        if (socketManager.connectionState.value !is ConnectionState.Connected) {<br>            Log.d(&quot;OfflineQueue&quot;, &quot;Cannot process queue: not connected&quot;)<br>            return<br>        }<br><br>        val iterator = queuedMessages.iterator()<br>        while (iterator.hasNext()) {<br>            val message = iterator.next()<br><br>            try {<br>                socketManager.emit(&quot;message:send&quot;, message.toJson())<br><br>                // Update status to sent<br>                messageDao.updateStatus(message.id, MessageStatus.SENT)<br><br>                // Remove from queue<br>                iterator.remove()<br>            } catch (e: Exception) {<br>                Log.e(&quot;OfflineQueue&quot;, &quot;Failed to send message: ${message.id}&quot;, e)<br><br>                // Mark as failed after max retries<br>                if (message.retryCount &gt;= 3) {<br>                    messageDao.updateStatus(message.id, MessageStatus.FAILED)<br>                    iterator.remove()<br>                }<br>            }<br>        }<br>    }<br><br>    private fun scheduleSync() {<br>        val syncWork = OneTimeWorkRequestBuilder&lt;MessageSyncWorker&gt;()<br>            .setConstraints(<br>                Constraints.Builder()<br>                    .setRequiredNetworkType(NetworkType.CONNECTED)<br>                    .build()<br>            )<br>            .setBackoffCriteria(<br>                BackoffPolicy.EXPONENTIAL,<br>                WorkRequest.MIN_BACKOFF_MILLIS,<br>                TimeUnit.MILLISECONDS<br>            )<br>            .build()<br><br>        WorkManager.getInstance(context)<br>            .enqueueUniqueWork(<br>                &quot;message_sync&quot;,<br>                ExistingWorkPolicy.KEEP,<br>                syncWork<br>            )<br>    }<br>}<br><br>class MessageSyncWorker(<br>    context: Context,<br>    params: WorkerParameters<br>) : CoroutineWorker(context, params) {<br><br>    override suspend fun doWork(): Result {<br>        val socketManager = SocketManager.getInstance(applicationContext)<br>        val offlineQueue = /* inject or retrieve instance */<br><br>        return try {<br>            if (socketManager.connectionState.value is ConnectionState.Connected) {<br>                offlineQueue.processQueue()<br>                Result.success()<br>            } else {<br>                Result.retry()<br>            }<br>        } catch (e: Exception) {<br>            Log.e(&quot;MessageSyncWorker&quot;, &quot;Sync failed&quot;, e)<br>            Result.retry()<br>        }<br>    }<br>}</pre><p>WorkManager ensures messages sync even if the app is closed, with automatic retry using exponential backoff. This creates a WhatsApp-like experience where messages eventually deliver regardless of network conditions.</p><h3>Performance Optimization: Production-Ready Patterns</h3><p>After deploying to production, these optimizations made the biggest impact on reliability and user experience:</p><p><strong>1. Exponential Backoff for Reconnection</strong></p><pre>private fun calculateReconnectDelay(attempt: Int): Long {<br>    val baseDelay = 1000L<br>    val maxDelay = 30000L<br>    val exponentialDelay = baseDelay * (2.0.pow(attempt)).toLong()<br>    return min(exponentialDelay, maxDelay)<br>}</pre><p>This prevents overwhelming the server during outages and reduces battery drain from rapid reconnection attempts.</p><p><strong>2. Message Batching for High-Frequency Updates</strong></p><pre>private val messageBuffer = mutableListOf&lt;Message&gt;()<br>private val batchInterval = 100L // milliseconds<br><br>private fun bufferMessage(message: Message) {<br>    messageBuffer.add(message)<br><br>    if (messageBuffer.size &gt;= 10 || /* time threshold */) {<br>        flushBuffer()<br>    }<br>}<br><br>private fun flushBuffer() {<br>    if (messageBuffer.isEmpty()) return<br><br>    val batch = messageBuffer.toList()<br>    messageBuffer.clear()<br><br>    _messages.value = _messages.value + batch<br>}</pre><p>Batching UI updates prevents frame drops during rapid message influx and improves scroll performance.</p><p><strong>3. Connection Pooling and Lifecycle Management</strong></p><p>Integrate Socket.IO lifecycle with Android components:</p><pre>class ChatViewModel(<br>    private val repository: ChatRepository,<br>    private val socketManager: SocketManager<br>) : ViewModel() {<br><br>    init {<br>        viewModelScope.launch {<br>            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                // Connect when UI is visible<br>                socketManager.connect(getAuthToken())<br>            }<br>        }<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        // Disconnect when ViewModel is destroyed<br>        socketManager.disconnect()<br>    }<br>}</pre><p>4.<strong> Memory Management Best Practices</strong></p><ul><li>Limit in-memory message cache to 500 messages; load older messages from database on-demand</li><li>Clear socket event listeners when disconnecting to prevent memory leaks</li><li>Use weak references for listeners that reference Activity/Fragment contexts</li></ul><h3>Production Metrics: Real-World Results</h3><p>After six months in production, here are the metrics that matter:</p><p><strong>Uptime &amp; Reliability:</strong></p><ul><li>99.5% uptime measured over 90 days</li><li>98.7% message delivery rate (including offline scenarios)</li><li>Average reconnection time: 2.3 seconds after network restoration</li></ul><p><strong>Performance:</strong></p><ul><li>Sub-200ms latency for message delivery in optimal conditions</li><li>50+ concurrent users supported per server instance</li><li>Zero message loss in offline queue (tested with intentional network interruptions)</li><li>Memory footprint: 45MB average with 500 cached messages</li></ul><p><strong>Common Pitfalls Avoided:</strong></p><ol><li>Don’t authenticate after connection — pass auth token during initial Socket.IO handshake to prevent race conditions</li><li>Never block the main thread — all socket operations should happen on background threads</li><li>Handle rapid connect/disconnect cycles — debounce connection state changes to prevent UI flicker</li><li>Don’t trust socket.connected() alone — maintain your own connection state based on actual event callbacks</li><li>Implement idempotency — server should handle duplicate message submissions gracefully using message IDs</li></ol><h3>Architecture Diagram</h3><p>Here’s a visual representation of the complete system architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mK-K-DsVrC-FrhrECgYVVQ.png" /></figure><p><strong>Data Flow:</strong></p><ol><li>User sends message → Repository (optimistic update) → SocketManager</li><li>SocketManager emits to server → Server broadcasts</li><li>Server response → SocketManager → Repository → UI update</li><li>If offline → OfflineQueue → WorkManager schedules retry</li></ol><h3>Conclusion: Key Takeaways</h3><p>Building production-ready real-time chat taught me that architecture trumps technology every time. Socket.IO is powerful, but without proper state management, offline handling, and performance optimization, even the best library will fail in production.</p><p><strong>When to use this architecture:</strong></p><ul><li>Building any real-time feature (chat, notifications, live updates)</li><li>Apps requiring offline-first capabilities</li><li>Systems needing high reliability and performance</li></ul><p><strong>When to reconsider:</strong></p><ul><li>Simple request-response patterns (use REST)</li><li>Very low message volume (polling might suffice)</li><li>Server infrastructure constraints (WebSocket requires different setup than REST)</li></ul><p><strong>Resources for deeper learning:</strong></p><ul><li>Socket.IO documentation: <a href="https://socket.io/docs/v4/">https://socket.io/docs/v4/</a></li><li>Android Architecture Components: <a href="https://developer.android.com/topic/architecture">https://developer.android.com/topic/architecture</a></li><li>WorkManager guide: <a href="https://developer.android.com/topic/libraries/architecture/workmanager">https://developer.android.com/topic/libraries/architecture/workmanager</a></li></ul><p>The patterns shared here scale from prototype to production. Start simple, measure constantly, and optimize based on real metrics — not assumptions. Your users will notice the difference.</p><p><strong>What real-time features are you building? Share your challenges and learnings in the comments.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf98428da615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Android Image Loader: A Deep Dive]]></title>
            <link>https://medium.com/@sjasmeet438/building-a-custom-android-image-loader-a-deep-dive-841d6d5b7abb?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/841d6d5b7abb</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 15:29:25 GMT</pubDate>
            <atom:updated>2025-10-28T15:29:25.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-f_mO6qGm3YQUGGEIVB8Q.png" /></figure><h3>Introduction</h3><p>After building a custom image loader that handles animated GIFs, WebP images, and static bitmaps with a three-tier caching system, I learned that sometimes reinventing the wheel is exactly what you need. While libraries like Glide, Picasso, and Coil are excellent choices for most projects, building your own image loader provides invaluable insights into Android’s image handling, memory management, and coroutine-based architectures.</p><p>Why build a custom solution? First, control over your app’s footprint matters when every kilobyte counts — popular image libraries can add 500KB+ to your APK. Second, it’s an exceptional learning opportunity that teaches you about caching strategies, bitmap manipulation, and concurrent programming. Finally, you gain complete control over features, optimizations, and the ability to tailor the solution specifically to your app’s needs without carrying unnecessary baggage.</p><p>In this article, I’ll walk you through building a production-ready image loader from scratch using Kotlin coroutines, implementing three-layer caching, and supporting both static and animated images.</p><h3>The Problem: When to Use Libraries vs. Custom Solutions</h3><p>The Android ecosystem offers mature image loading libraries that handle edge cases, memory management, and platform quirks you might not even know exist. So when does building custom make sense?</p><p><strong>Use established libraries when:</strong></p><ul><li>You need battle-tested code for production apps with millions of users</li><li>Time-to-market is critical and your team needs to focus on core features</li><li>You require advanced features like video thumbnails, SVG support, or complex transformation pipelines</li><li>Your app handles diverse image sources (network, local storage, content providers) with varying requirements</li></ul><p><strong>Build custom when:</strong></p><ul><li>App size is a critical concern (every KB matters for emerging markets or lite versions)</li><li>You have specific requirements that libraries don’t address efficiently</li><li>You’re building a learning project or want deep understanding of Android internals</li><li>Your image loading needs are straightforward and you want zero dependencies</li><li>You need complete control over caching strategies and memory management</li></ul><p>For my use case, I wanted to deeply understand how image loading works under the hood, optimize for specific animated format handling (GIF and WebP), and keep my app lean. The learning experience alone justified the investment, and I gained insights that make me better at using libraries too — you can’t optimize what you don’t understand.</p><p>The key question isn’t “Can I build this?” but rather “Should I build this?” Consider your team’s expertise, project timeline, and maintenance burden. Building custom means you own every bug and performance issue, but it also means you control every optimization.</p><h3>Architecture: Three-Layer Caching Strategy</h3><p>The architecture follows a simple but effective three-layer approach: memory cache → disk cache → network download. Each layer acts as a fallback, creating a waterfall that prioritizes speed while ensuring reliability.</p><p><strong>Layer 1: Memory Cache (Fastest)</strong> Uses Android’s LruCache to store recently accessed images in RAM. This provides instant access with zero I/O overhead. The cache size is automatically set to 1/8 of available heap memory, balancing performance with memory pressure. For animated images, we store only the raw bytes and metadata, not decoded frames—implementing lazy frame decoding to avoid memory explosion.</p><p><strong>Layer 2: Disk Cache (Fast)</strong> When images aren’t in memory, we check persistent storage. Files are cached in the app’s cache directory with MD5-hashed filenames to avoid collisions. We preserve the original format (PNG for static, GIF/WebP for animated) to avoid lossy conversions. This layer survives app restarts but respects system cache cleanup policies.</p><p><strong>Layer 3: Network Download (Fallback)</strong> If both caches miss, we download from the network using Kotlin coroutines on the IO dispatcher. The implementation detects image formats automatically, supporting static images (PNG, JPEG) and animated formats (GIF, WebP). Downloads use reasonable timeouts (5 seconds) to fail fast on poor connections.</p><p>Flow diagram:</p><pre>Request Image<br>    ↓<br>Memory Cache? → Yes → Return<br>    ↓ No<br>Disk Cache? → Yes → Store in Memory → Return<br>    ↓ No<br>Download → Store in Disk + Memory → Return</pre><p>This waterfall approach ensures maximum performance while minimizing bandwidth usage. Each layer feeds back to previous layers, so subsequent requests get progressively faster. The beauty is in its simplicity: check fast sources first, fall back to slower ones, and populate faster caches along the way.</p><h3>Implementation: Download Layer</h3><p>The download layer is the foundation, handling network requests with Kotlin coroutines and automatic format detection:</p><pre>class ImageDownloader {<br>    suspend fun download(url: String): ImageData? = withContext(Dispatchers.IO) {<br>        try {<br>            val connection = URL(url).openConnection()<br>            connection.connectTimeout = 5000<br>            connection.readTimeout = 5000<br><br>            val bytes = connection.getInputStream().use { it.readBytes() }<br><br>            // Detect animated format (GIF or WebP)<br>            val animatedFormat = AnimatedImageDecoderFactory.detectFormat(bytes)<br><br>            if (animatedFormat != null) {<br>                val decoder = AnimatedImageDecoderFactory.createDecoder(bytes, animatedFormat)<br><br>                return@withContext ImageData.AnimatedImage(<br>                    bytes = bytes,<br>                    format = animatedFormat,<br>                    frameCount = decoder.frameCount,<br>                    width = decoder.width,<br>                    height = decoder.height<br>                ).also { decoder.release() }<br>            } else {<br>                // Static image<br>                val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)<br>                if (bitmap != null) ImageData.StaticImage(bitmap) else null<br>            }<br>        } catch (e: Exception) {<br>            null<br>        }<br>    }<br>}</pre><p>Key design decisions: Using withContext(Dispatchers.IO) ensures downloads don&#39;t block the main thread. The 5-second timeout prevents hanging on slow connections. We return a sealed class ImageData that elegantly handles both static bitmaps and animated images. Format detection happens by reading byte signatures (GIF magic bytes: 47 49 46, WebP: 52 49 46 46).</p><p>For animated images, we store raw bytes instead of decoding all frames upfront — this is crucial for memory efficiency. A 2MB GIF might have 50 frames; decoding all would consume 100MB+ of RAM. Instead, we extract only metadata (frame count, dimensions) and defer frame decoding until render time.</p><h3>Implementation: Memory Cache Layer</h3><p>The memory cache uses Android’s built-in LruCache, which automatically evicts least-recently-used items when memory pressure increases:</p><pre>object MemoryCache {<br>    private val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()<br>    private val cacheSize = maxMemory / 8<br><br>    private val cache = object : LruCache&lt;String, ImageData&gt;(cacheSize) {<br>        override fun sizeOf(key: String, data: ImageData): Int {<br>            return when (data) {<br>                is ImageData.StaticImage -&gt; data.bitmap.byteCount / 1024<br>                is ImageData.AnimatedImage -&gt; {<br>                    // Only count bytes, not decoded frames (lazy decoding)<br>                    (data.bytes.size / 1024) + 100 // 100KB overhead estimate<br>                }<br>            }<br>        }<br>    }<br><br>    fun get(key: String): ImageData? = cache.get(key)<br>    fun put(key: String, data: ImageData) {<br>        if (get(key) == null) cache.put(key, data)<br>    }<br>    fun clear() = cache.evictAll()<br>}</pre><p>The critical method is sizeOf(), which tells LruCache how much &quot;space&quot; each entry consumes. For static images, we use bitmap.byteCount—the actual memory footprint. For animated images, we count only the compressed bytes plus a small overhead estimate (100KB for decoder metadata).</p><p>Using 1/8 of max heap is a conservative choice that balances caching benefits with avoiding OutOfMemoryErrors. On a device with 512MB heap, that’s 64MB for image caching — enough for dozens of high-res images.</p><p>The singleton pattern (object) ensures a single cache instance app-wide, preventing duplicate memory usage. Keys include transformation hashes, so a rounded-corner version and original are cached separately.</p><h3>Implementation: Disk Cache Layer</h3><p>The disk cache provides persistence across app restarts, using the app’s cache directory which the system can clear when storage runs low:</p><pre>class DiskCache(private val context: Context) {<br>    private val cacheDir = File(context.cacheDir, &quot;image_cache&quot;).apply {<br>        if (!exists()) mkdirs()<br>    }<br><br>    private fun urlToFilename(url: String, extension: String = &quot;.png&quot;): String {<br>        val md = MessageDigest.getInstance(&quot;MD5&quot;)<br>        val hash = md.digest(url.toByteArray())<br>        return hash.joinToString(&quot;&quot;) { &quot;%02x&quot;.format(it) } + extension<br>    }<br><br>    suspend fun get(url: String): ImageData? = withContext(Dispatchers.IO) {<br>        // Try animated formats first<br>        for (ext in listOf(&quot;.gif&quot;, &quot;.webp&quot;)) {<br>            val animatedFile = File(cacheDir, urlToFilename(url, ext))<br>            if (animatedFile.exists()) {<br>                val bytes = animatedFile.readBytes()<br>                val format = AnimatedImageDecoderFactory.detectFormat(bytes)<br><br>                if (format != null) {<br>                    val decoder = AnimatedImageDecoderFactory.createDecoder(bytes, format)<br>                    return@withContext ImageData.AnimatedImage(<br>                        bytes = bytes,<br>                        format = format,<br>                        frameCount = decoder.frameCount,<br>                        width = decoder.width,<br>                        height = decoder.height<br>                    ).also { decoder.release() }<br>                }<br>            }<br>        }<br><br>        // Fallback to static image<br>        val file = File(cacheDir, urlToFilename(url, &quot;.png&quot;))<br>        if (file.exists()) {<br>            val bitmap = BitmapFactory.decodeFile(file.absolutePath)<br>            return@withContext if (bitmap != null) ImageData.StaticImage(bitmap) else null<br>        }<br>        null<br>    }<br><br>    suspend fun put(url: String, data: ImageData) = withContext(Dispatchers.IO) {<br>        when (data) {<br>            is ImageData.StaticImage -&gt; {<br>                val file = File(cacheDir, urlToFilename(url, &quot;.png&quot;))<br>                FileOutputStream(file).use { out -&gt;<br>                    data.bitmap.compress(CompressFormat.PNG, 90, out)<br>                }<br>            }<br>            is ImageData.AnimatedImage -&gt; {<br>                val ext = when (data.format) {<br>                    AnimatedFormat.GIF -&gt; &quot;.gif&quot;<br>                    AnimatedFormat.WEBP -&gt; &quot;.webp&quot;<br>                }<br>                val file = File(cacheDir, urlToFilename(url, ext))<br>                file.writeBytes(data.bytes)<br>            }<br>        }<br>    }<br>}</pre><p>MD5 hashing converts URLs into safe filenames while preventing collisions. We preserve original formats for animated images (storing raw GIF/WebP bytes) to avoid re-encoding overhead. For static images, PNG compression at 90% quality balances file size with visual fidelity.</p><p>The get() method tries animated formats first, then falls back to static—this handles cases where image format might change at the same URL (rare, but defensive programming).</p><h3>Complete Implementation: Orchestrating the Layers</h3><p>The ImageLoader class ties everything together, implementing the waterfall logic:</p><pre>class ImageLoader(private val context: Context) {<br>    private val downloader = ImageDownloader()<br>    private val diskCache = DiskCache(context)<br>    private val prefetchJobs = mutableMapOf&lt;String, Job&gt;()<br><br>    suspend fun load(<br>        url: String,<br>        transformation: ImageTransformation = ImageTransformation.None<br>    ): ImageData? {<br>        val cacheKey = &quot;$url-${transformation.hashCode()}&quot;<br><br>        // 1. Check memory cache<br>        MemoryCache.get(cacheKey)?.let { return it }<br><br>        // 2. Check disk cache<br>        diskCache.get(url)?.let { data -&gt;<br>            val transformed = ImageTransformer.apply(data, transformation, context)<br>            MemoryCache.put(cacheKey, transformed)<br>            return transformed<br>        }<br><br>        // 3. Download and transform<br>        downloader.download(url)?.let { data -&gt;<br>            val transformed = ImageTransformer.apply(data, transformation, context)<br>            MemoryCache.put(cacheKey, transformed)<br>            diskCache.put(url, data) // Store original<br>            return transformed<br>        }<br><br>        return null<br>    }<br><br>    fun prefetch(url: String, scope: CoroutineScope) {<br>        if (prefetchJobs.containsKey(url)) return<br><br>        prefetchJobs[url] = scope.launch {<br>            load(url)<br>        }<br>    }<br>}</pre><p>The load flow is beautifully simple: try memory, then disk, then download. Each stage falls through to the next on miss. Transformations (rounded corners, circles, blur) are applied lazily and cached separately with unique keys.</p><p>The prefetch functionality is a performance bonus — you can preload images before they’re needed, warming up caches. It tracks jobs to prevent duplicate prefetch requests and allows cancellation.</p><p>Notice we store the original in disk cache but transformed versions in memory cache. This saves disk space while allowing multiple transformed variants of the same image in memory.</p><h3>When to Use What: Decision Matrix</h3><p>Use Glide/Coil/Picasso when:</p><ul><li>Building production apps that need reliability over customization</li><li>You need advanced features (transformations, video thumbnails, SVG, HTTP caching headers)</li><li>Team lacks deep Android/imaging expertise</li><li>Time-to-market is more valuable than APK size</li></ul><p>Build custom when:</p><ul><li>APK size is critical (lite apps, emerging markets)</li><li>Learning and understanding are priorities</li><li>You have simple, well-defined requirements</li><li>You need specific optimizations that libraries don’t provide</li></ul><h3>Conclusion</h3><p>Building a custom image loader taught me more about Android than weeks of reading documentation. You gain intuition about memory management, coroutine architectures, and the tradeoffs libraries make on your behalf.</p><p>Is it production-ready? For apps with straightforward image needs, absolutely. Would I use it in a social media app with complex requirements? Probably not — I’d reach for Glide and appreciate all the edge cases it handles.</p><p>The complete source code is available on GitHub: <a href="https://github.com/jasi381/Custom-Image-Loader.git">https://github.com/jasi381/Custom-Image-Loader.git</a></p><p>Key takeaways: three-layer caching is powerful yet simple, lazy frame decoding is essential for animated images, and sometimes the best way to learn is to build it yourself.</p><p><strong>Here is small demo</strong></p><p><a href="https://www.youtube.com/watch?v=1jLwlI-x9Z4">https://www.youtube.com/watch?v=1jLwlI-x9Z4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841d6d5b7abb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Health Connect SDK in Android: A Simplified Guide]]></title>
            <link>https://medium.com/@sjasmeet438/integrating-health-connect-sdk-in-android-a-simplified-guide-964aafb26397?source=rss-8b9e48d1942f------2</link>
            <guid isPermaLink="false">https://medium.com/p/964aafb26397</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[health-connect]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-health-app]]></category>
            <dc:creator><![CDATA[Jasmeet Singh]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 05:50:11 GMT</pubDate>
            <atom:updated>2025-10-20T05:57:13.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh6VYIJF4UM3LXOkt7F81g.png" /><figcaption>Visualising the simplest Health Connect architecture</figcaption></figure><p>When Google launched Health Connect SDK in 2022, it promised to unify health data across Android apps. After implementing it in production, I realized the official documentation overcomplicates things with complex architectures.</p><p><strong>You don’t need repositories, use cases, or multi-layer architectures to get started.</strong></p><p>This guide shows you the simplest way: <strong>UI → ViewModel → Health Connect</strong>. That’s it.</p><h3>What You’ll Build</h3><p>A health tracking screen that:</p><ul><li>Requests permissions from users</li><li>Reads heart rate, sleep hours, and step count</li><li>Shows loading states while fetching data</li><li>Handles errors gracefully with retry options</li></ul><p><strong>Tech Stack:</strong> Jetpack Compose, ViewModel, Health Connect SDK 1.1.0, Kotlin Coroutines</p><h3>Understanding Health Connect</h3><p>Health Connect is Android’s centralized health data platform. Think of it as a middleman between your app and fitness devices.</p><p><strong>Before Health Connect:</strong></p><ul><li>Each fitness app stored data separately</li><li>No data sharing between apps</li><li>Developers built custom integrations for each device</li></ul><p><strong>After Health Connect:</strong></p><ul><li>Single source of truth for health data</li><li>Standardized data types (heart rate, sleep, steps)</li><li>Works across devices and manufacturers</li></ul><h3>When Should You Use It?</h3><p>✅ <strong>Use Health Connect for:</strong> Fitness tracking, healthcare monitoring, wellness platforms</p><p>❌ <strong>Don’t use it for:</strong> Simple step counting (use ActivityRecognition API), non-health apps</p><p><strong>Setup Process (10 Minutes)</strong></p><p><strong>Step 1: Add Dependencies</strong></p><pre>dependencies {<br>    implementation(&quot;androidx.health.connect:connect-client:1.1.0&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0&quot;)<br>}</pre><p><strong>Step 2: Configure AndroidManifest.xml</strong></p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    <br>    &lt;uses-permission android:name=&quot;android.permission.health.READ_HEART_RATE&quot;/&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.health.READ_SLEEP&quot;/&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.health.READ_STEPS&quot;/&gt;<br>    <br>    &lt;application&gt;<br>        &lt;!-- This activity-alias is REQUIRED --&gt;<br>        &lt;activity-alias<br>            android:name=&quot;ViewPermissionUsageActivity&quot;<br>            android:exported=&quot;true&quot;<br>            android:targetActivity=&quot;.MainActivity&quot;<br>            android:permission=&quot;android.permission.START_VIEW_PERMISSION_USAGE&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.VIEW_PERMISSION_USAGE&quot;/&gt;<br>                &lt;category android:name=&quot;android.intent.category.HEALTH_PERMISSIONS&quot;/&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity-alias&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;<br>```<br><br>**Critical:** Without the activity-alias, permission requests fail silently. Don&#39;t skip it!</pre><p><strong>Step 3: Install Health Connect</strong></p><ul><li><strong>On Android 14 and above:</strong><br>Health Connect is already <strong>built into the system</strong> (package name: com.google.android.apps.healthdata).<br>You <strong>don’t need to install it from the Play Store</strong>, but you must still include the required activity-alias and handle permission requests as usual.</li><li><strong>On Android 13 and below:</strong><br>You must <strong>manually install Health Connect</strong> from the Play Store before integration will work.<br>Go to <strong>Play Store → Search “Health Connect” → Install it.</strong></li></ul><h3><strong>Building the ViewModel</strong></h3><p><strong>Define Ui State</strong></p><pre>data class HealthUiState(<br>    val isLoading: Boolean = false,<br>    val error: String? = null,<br>    val heartRate: Int? = null,<br>    val steps: Long? = null,<br>    val sleepHours: Double? = null,<br>    val permissionsGranted: Boolean = false<br>)</pre><p>This represents everything your UI needs to know. When any field changes, the UI automatically updates.</p><h3><strong>The ViewModel Core</strong></h3><p>Your ViewModel does four things:</p><p><strong>1. Iintialize Health Connect Client</strong></p><pre>private val healthConnectClient = HealthConnectClient.getOrCreate(application)</pre><p><strong>2. Define Required Permissions</strong></p><pre>val permissions = setOf(<br>    HealthPermission.getReadPermission(HeartRateRecord::class),<br>    HealthPermission.getReadPermission(SleepSessionRecord::class),<br>    HealthPermission.getReadPermission(StepsRecord::class),<br>)</pre><p><strong>3. Handle Permission Results</strong></p><pre>fun onPermissionsResult(granted: Set&lt;String&gt;) {<br>    _uiState.update { <br>        it.copy(permissionsGranted = granted.containsAll(permissions)) <br>    }<br>    <br>    if (_uiState.value.permissionsGranted) {<br>        loadHealthData()<br>    }<br>}</pre><p><strong>4. Fetch Health Data</strong></p><pre>fun loadHealthData() {<br>    viewModelScope.launch {<br>        _uiState.update { it.copy(isLoading = true, error = null) }<br>        <br>        try {<br>            val heartRate = readLatestHeartRate()<br>            val steps = readTodaySteps()<br>            val sleep = readLastNightSleep()<br>            <br>            _uiState.update {<br>                it.copy(<br>                    isLoading = false,<br>                    heartRate = heartRate,<br>                    steps = steps,<br>                    sleepHours = sleep<br>                )<br>            }<br>        } catch (e: Exception) {<br>            _uiState.update {<br>                it.copy(isLoading = false, error = &quot;Failed: ${e.message}&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Reading Health Data</h3><p><strong>Heart Rate:</strong></p><pre>private suspend fun readLatestHeartRate(startTime: Instant, endTime: Instant): Int? {<br>    val response = healthConnectClient.readRecords(<br>        ReadRecordsRequest(<br>            recordType = HeartRateRecord::class,<br>            timeRangeFilter = TimeRangeFilter.between(startTime, endTime)<br>        )<br>    )<br>    return response.records.lastOrNull()?.samples?.lastOrNull()?.beatsPerMinute?.toInt()<br>}</pre><p><strong>Steps (Aggregated):</strong></p><pre>private suspend fun readTodaySteps(startTime: Instant, endTime: Instant): Long? {<br>    val response = healthConnectClient.aggregate(<br>        AggregateRequest(<br>            metrics = setOf(StepsRecord.COUNT_TOTAL),<br>            timeRangeFilter = TimeRangeFilter.between(startTime, endTime)<br>        )<br>    )<br>    return response[StepsRecord.COUNT_TOTAL]<br>}</pre><p><strong>Sleep Duration:</strong></p><pre>private suspend fun readLastNightSleep(): Double? {<br>    val now = Instant.now()<br>    val yesterday = now.minus(1, ChronoUnit.DAYS)<br>    <br>    val response = healthConnectClient.readRecords(<br>        ReadRecordsRequest(<br>            recordType = SleepSessionRecord::class,<br>            timeRangeFilter = TimeRangeFilter.between(yesterday, now)<br>        )<br>    )<br>    <br>    return response.records.lastOrNull()?.let { session -&gt;<br>        Duration.between(session.startTime, session.endTime).toHours().toDouble()<br>    }<br>}</pre><h3>Building the UI</h3><p><strong>Permission Flow</strong></p><pre>@Composable<br>fun HealthScreen(viewModel: HealthViewModel = viewModel()) {<br>    val uiState by viewModel.uiState.collectAsState()<br>    <br>    val permissionLauncher = rememberLauncherForActivityResult(<br>        contract = PermissionController.createRequestPermissionResultContract()<br>    ) { granted -&gt;<br>        viewModel.onPermissionsResult(granted)<br>    }<br>    <br>    if (!uiState.permissionsGranted) {<br>        Button(onClick = { permissionLauncher.launch(viewModel.permissions) }) {<br>            Text(&quot;Grant Health Permissions&quot;)<br>        }<br>    } else {<br>        // Show health data<br>    }<br>}</pre><p><strong>Displaying Data</strong></p><pre>if (uiState.isLoading) {<br>    CircularProgressIndicator()<br>}<br><br>if (uiState.error != null) {<br>    Text(text = uiState.error!!, color = MaterialTheme.colorScheme.error)<br>    Button(onClick = { viewModel.loadHealthData() }) {<br>        Text(&quot;Retry&quot;)<br>    }<br>}<br><br>if (!uiState.isLoading &amp;&amp; uiState.error == null) {<br>    HealthDataCard(&quot;Heart Rate&quot;, uiState.heartRate?.toString() ?: &quot;No data&quot;, &quot;BPM&quot;)<br>    HealthDataCard(&quot;Steps Today&quot;, uiState.steps?.toString() ?: &quot;No data&quot;, &quot;steps&quot;)<br>    HealthDataCard(&quot;Sleep&quot;, uiState.sleepHours?.let { &quot;%.1f&quot;.format(it) } ?: &quot;No data&quot;, &quot;hours&quot;)<br>}</pre><h3>Three Real Problems You’ll Face</h3><p><strong>Problem 1: Health Connect Not Installed</strong></p><p><strong>Solution:</strong> Check availability before requesting permissions:</p><pre>LaunchedEffect(Unit) {<br>    if (!viewModel.checkAvailability()) {<br>        Toast.makeText(context, &quot;Install Health Connect from Play Store&quot;, Toast.LENGTH_LONG).show()<br>    }<br>}</pre><p><strong>Problem 2: No Data Available</strong></p><p><strong>Solution:</strong> Handle nulls gracefully:</p><pre>HealthDataCard(<br>    title = &quot;Heart Rate&quot;,<br>    value = uiState.heartRate?.toString() ?: &quot;No data available&quot;,<br>    unit = if (uiState.heartRate != null) &quot;BPM&quot; else &quot;&quot;<br>)</pre><p><strong>Problem 3: Partial Permission Grants</strong></p><p><strong>Solution:</strong> Handle each metric independently:</p><pre>if (uiState.heartRate != null) { /* Show heart rate card */ }<br>if (uiState.steps != null) { /* Show steps card */ }<br>if (uiState.sleepHours != null) { /* Show sleep card */ }</pre><h3>Common Mistakes to Avoid</h3><p>❌ Assuming all devices work the same<br>❌ Not explaining why you need permissions<br>❌ Requesting too many permissions at once<br>❌ Forgetting permissions in AndroidManifest.xml<br>❌ Not testing without Health Connect installed</p><h3>Key Takeaways</h3><p>✅ Start with simple ViewModel → UI architecture<br>✅ Handle permissions granularly<br>✅ Always check Health Connect availability<br>✅ Show helpful error messages<br>✅ Test on real devices with real data</p><p>Health Connect is powerful once you understand its quirks. Start simple, test thoroughly, and iterate based on user feedback.</p><p><strong>Resources:</strong></p><ul><li><a href="https://developer.android.com/guide/health-and-fitness/health-connect">Official Documentation</a></li><li><a href="https://github.com/android/health-samples">Sample Apps</a></li></ul><p><strong>Full Code on Github</strong> : <a href="https://github.com/jasi381/Health-Connect">https://github.com/jasi381/Health-Connect</a></p><p><em>Questions? Drop a comment below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964aafb26397" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>