<?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 Irsath Kareem on Medium]]></title>
        <description><![CDATA[Stories by Irsath Kareem on Medium]]></description>
        <link>https://medium.com/@irsathkareem?source=rss-8bbb0c9e3eeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YqrqxA6Ny0JpSDQ0CxJagA.jpeg</url>
            <title>Stories by Irsath Kareem on Medium</title>
            <link>https://medium.com/@irsathkareem?source=rss-8bbb0c9e3eeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:08:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@irsathkareem/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[Implementing Uniform and Progressive Blur Effects in Jetpack Compose Using Modifier.blur]]></title>
            <link>https://medium.com/@irsathkareem/implementing-uniform-and-progressive-blur-effects-in-jetpack-compose-using-modifier-blur-c30b8293ca60?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c30b8293ca60</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[blur-effect-android]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 03:56:48 GMT</pubDate>
            <atom:updated>2026-10-23T03:56:48.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5LifYXNMVuiRsss2gERlg.png" /><figcaption>Implementing Uniform and Progressive Blur Effects in Jetpack Compose Using Modifier.blur</figcaption></figure><p>Blur effects soften visual details, create photographic depth of field, and draw focus to foreground UI elements. In Jetpack Compose, use Modifier.blur to blur the content drawn inside a composable, including images, shapes, text, and layout containers. Applying Modifier.blur renders the composable into a separate graphics layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RIM0RyHShHOa5OPi.png" /><figcaption><em>Left: the original image. Center: the image with a uniform blur applied across the whole surface. Right: the image with a progressive blur that is sharp at the top and increases toward the bottom</em></figcaption></figure><p>Depending on your design goals, you can vary the blur in two ways:</p><ul><li><strong>Uniform blur</strong>: Applies a constant blur radius across the entire composable, either equally on both axes or with independent horizontal and vertical radii (radiusX, radiusY).</li><li><strong>Progressive blur</strong>: Varies the blur radius spatially across the composable using BlurRadiusSpec gradients or a custom Shader.</li></ul><blockquote><strong><em>Note</em></strong><em>: </em><em>Modifier.blur blurs the content that a composable draws itself: its images, text, shapes, and child composables. This is sometimes called a surface or layer blur, as distinct from a backdrop blur, which blurs whatever is drawn behind a composable. This page covers surface blurs.</em></blockquote><h3>Apply a uniform blur</h3><blockquote><strong><em>Note</em></strong><em>: The examples in this section also pass an </em><em>edgeTreatment that clips the blurred result to rounded corners. For more information, see Control edge clipping with </em><em>BlurredEdgeTreatment.</em></blockquote><p>To apply a constant blur across an entire composable, pass a Dp radius to Modifier.blur. Pass a single radius value to blur content equally along both the horizontal (X) and vertical (Y) axes:</p><pre>@Composable<br>fun UniformBlurExample() {<br>    Image(<br>        painter = painterResource(id = R.drawable.dog),<br>        contentDescription = stringResource(id = R.string.dog_content_description),<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .size(150.dp)<br>            .blur(<br>                radius = 8.dp,<br>                edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp)),<br>            ),<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*4WN_WL_nw54KBHu1.png" /><figcaption><em>A dog uniformly blurred on both horizontal and vertical axes</em></figcaption></figure><p>To create a directional motion-blur effect, pass separate radiusX and radiusY values to Modifier.blur. Both radiusX and radiusY must be greater than 0.dp for the blur effect to apply, as shown in the following example:</p><pre>@Composable<br>fun DirectionalBlurExample() {<br>    Image(<br>        painter = painterResource(id = R.drawable.dog),<br>        contentDescription = stringResource(id = R.string.dog_content_description),<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .size(150.dp)<br>            .blur(<br>                radiusX = 10.dp,<br>                radiusY = 2.dp,<br>                edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp)),<br>            ),<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*UiyFMll91BxKNu3T.png" /><figcaption><em>A square image of a dog with a strong horizontal motion blur effect.</em></figcaption></figure><h3>Apply a progressive blur</h3><blockquote><strong><em>Note</em></strong><em>: Progressive blur APIs (</em><em>BlurRadiusSpec, </em><em>BlurStop, and the </em><em>Modifier.blur { } configuration block) are available in </em><em>androidx.compose.ui:ui 1.13.0-beta01 and higher.</em></blockquote><p>A progressive blur varies the blur radius across a composable, creating a smooth transition between sharp and blurred regions.</p><p>Pass a BlurRadiusSpec to Modifier.blur. For example, use BlurRadiusSpec.verticalGradient with startRadius = 0.dp and endRadius = 6.dp to keep the top of an image sharp while progressively blurring it toward the bottom, as shown in the following example:</p><pre>@Composable<br>fun ProgressiveBlurExample() {<br>    Image(<br>        painter = painterResource(id = R.drawable.dog),<br>        contentDescription = stringResource(id = R.string.dog_content_description),<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .size(150.dp)<br>            .blur(<br>                // Sharp at the top (0.dp), progressively blurred toward the bottom (6.dp)<br>                blurRadiusSpec = BlurRadiusSpec.verticalGradient(<br>                    startRadius = 0.dp,<br>                    endRadius = 6.dp,<br>                ),<br>                edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp)),<br>            ),<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*gGc3pAI44YusmQaW.png" /><figcaption><em>An image of a dog that is sharp at the top and gradually becomes blurred toward the bottom.</em></figcaption></figure><h3>Specify blur gradients with BlurRadiusSpec</h3><pre>| BlurRadiusSpec factory | Description |<br>|---|---|<br>|BlurRadiusSpec.verticalGradient | Smoothly changes the blur radius vertically from top (0f) to bottom (1f) across the layer. |<br>|BlurRadiusSpec.horizontalGradient | Smoothly changes the blur radius horizontally from the left edge (0f) to the right edge (1f). |<br>|BlurRadiusSpec.linearGradient | Applies a directional blur transition along a straight line connecting specific DpOffset coordinates. |<br>|BlurRadiusSpec.radialGradient	| Spreads the blur outward from a focal point toward the fallOffRadius boundary. |<br>|BlurRadiusSpec.uniform |	Applies an even blur radius across the entire layer. |<br>|BlurRadiusSpec.shader	| Uses a custom Shader&#39;s alpha channel to control and scale the maxRadius at each pixel. |</pre><h3>Customize blur distribution with BlurStop</h3><p>Standard gradient blurs interpolate linearly between 0f and 1f. To customize the blur distribution across a surface, such as blurring multiple edges or keeping a middle section completely sharp, pass a List&lt;BlurStop&gt; containing 2 to 16 BlurStop entries to verticalGradient, horizontalGradient, linearGradient, or radialGradient. Define the following for each BlurStop entry:</p><ul><li>fraction: The relative position along the gradient from 0.0f to 1.0f. Stops are sorted automatically by fraction.</li><li>radius: The blur radius in Dp applied at that fraction position.</li></ul><p>For example, four stops blur the top and bottom edges of an image while keeping the middle completely sharp, as shown in the following example:</p><pre>@Composable<br>fun MultiStopBlurExample() {<br>    Image(<br>        painter = painterResource(id = R.drawable.dog),<br>        contentDescription = stringResource(id = R.string.dog_content_description),<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .size(150.dp)<br>            .blur(<br>                // Blurred at the top and bottom edges, sharp in the middle (0.3f..0.7f)<br>                blurRadiusSpec = BlurRadiusSpec.verticalGradient(<br>                    stops = listOf(<br>                        BlurStop(fraction = 0.0f, radius = 20.dp),<br>                        BlurStop(fraction = 0.3f, radius = 0.dp),<br>                        BlurStop(fraction = 0.7f, radius = 0.dp),<br>                        BlurStop(fraction = 1.0f, radius = 20.dp),<br>                    ),<br>                ),<br>                edgeTreatment = BlurredEdgeTreatment.Unbounded,<br>            ),<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*PqsmwtKELC7sB55b.png" /><figcaption><em>An image of a dog with blurred top and bottom edges while keeping the middle horizontal strip in sharp focus.</em></figcaption></figure><h3>Configure layer properties with BlurScope</h3><p>Instead of passing blurRadiusSpec directly, you can pass a configuration block to Modifier.blur { … }. This block runs inside BlurScope, which gives you direct access to layout density and the following properties:</p><ul><li>size: DpSize: The measured width and height of the blurred layer in Dp, which defines the coordinate space for gradient geometry.</li><li>blurRadiusSpec: BlurRadiusSpec: The blur radius configuration across the surface. Defaults to BlurRadiusSpec.uniform(0.dp) (no blur).</li><li>edgeTreatment: BlurredEdgeTreatment: Strategy used to sample and clip pixels outside content bounds. Defaults to BlurredEdgeTreatment.Rectangle.</li><li>alpha: Float: Opacity of the blurred layer in the 0f..1f range. Defaults to 1f.</li></ul><p>Because the BlurScope block runs during the graphics layer phase, after measurement and layout, you can compute gradient geometry from size without triggering recomposition.</p><blockquote><strong><em>Note</em></strong><em>: Uniform blurs require Android 12 (API level 31) and higher, and progressive blurs require Android 13 (API level 33) and higher. On lower versions, Compose renders the content unblurred, though BlurredEdgeTreatment shape clipping and alpha settings still apply.</em></blockquote><h3>Control edge clipping with BlurredEdgeTreatment</h3><p>Because blurring samples neighboring pixels within the blur radius, the blurred output extends beyond the original content bounds by the blur radius. BlurredEdgeTreatment determines how pixels outside the original bounds are sampled and whether the result is clipped to a shape.</p><p>BlurredEdgeTreatment works with both uniform and progressive blurs:</p><p><strong>BlurredEdgeTreatment.Rectangle (default)</strong></p><p>Behaviour: Clips the blur result to the rectangular bounds of the original content and samples the closest edge pixels (TileMode.Clamp).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*DmKyoEjTEN2hXxQI.png" /><figcaption><strong>BlurredEdgeTreatment.Rectangle</strong></figcaption></figure><p><strong>BlurredEdgeTreatment(shape)</strong></p><p>Behaviour: Clips the blur result to the specified Shape (such as RoundedCornerShape(8.dp)) and samples the closest edge pixels (TileMode.Clamp). Keeps the blurred result sharp at the shape boundary without bleeding outside the original bounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*WvqYTxiq9QkfMhMw.png" /><figcaption><strong>BlurredEdgeTreatment(RoundedCornerShape(8.dp))</strong></figcaption></figure><p><strong>BlurredEdgeTreatment.Unbounded</strong></p><p>Behaviour: Doesn’t clip the blur result (TileMode.Decal). Pixels outside the content bounds sample transparent black, making the outer edges of the image appear fuzzy and blurred beyond the original bounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*UFTB-isMWnz_4Dng.png" /><figcaption><strong>BlurredEdgeTreatment.Unbounded</strong></figcaption></figure><p>To see how these APIs combine in complete UI patterns, such as fading the edges of scrolling content, spotlighting a focal point, or masking a blur with a custom shader, see <a href="https://medium.com/@irsathkareem/custom-blur-effects-in-jetpack-compose-using-linear-radial-and-shader-gradients-5667a4434396">Custom Blur Effects in Jetpack Compose Using Linear, Radial, and Shader Gradients</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c30b8293ca60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Blur Effects in Jetpack Compose Using Linear, Radial, and Shader Gradients]]></title>
            <link>https://medium.com/@irsathkareem/custom-blur-effects-in-jetpack-compose-using-linear-radial-and-shader-gradients-5667a4434396?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5667a4434396</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[blur]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 03:45:42 GMT</pubDate>
            <atom:updated>2026-10-23T03:58:25.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RA86TH_b6pOSbLrIFWoCA.png" /><figcaption>Custom Blur Effects in Jetpack Compose</figcaption></figure><p>The following sections show how to combine Modifier.blur, BlurRadiusSpec, BlurStop, and BlurScope for common UI patterns. For an introduction to these APIs, see <a href="https://medium.com/@irsathkareem/implementing-uniform-and-progressive-blur-effects-in-jetpack-compose-using-modifier-blur-c30b8293ca60">Implementing Uniform and Progressive Blur Effects in Jetpack Compose Using Modifier.blur</a></p><h3>Blur the edges of scrolling or draggable content</h3><p>When displaying a scrolling list, carousel, or picker, you can use multi-stop progressive blurs to soften items near the container edges while keeping the active center region in sharp focus.</p><h3>Fade top and bottom edges of a scrolling list</h3><p>To soften items as they scroll into and out of a vertical list’s viewport, apply BlurRadiusSpec.verticalGradient with BlurStop entries to the LazyColumn. In the following example, which scrolls song lyrics line by line, the 0.dp stops between 0.42f and 0.58f keep the active line in the center sharp while the lines toward the top and bottom edges progressively blur out:</p><pre>@Composable<br>fun SongListTopBottomBlurExample(lyrics: List&lt;String&gt;) {<br>    // ...<br>    LazyColumn(<br>        state = listState,<br>        flingBehavior = flingBehavior,<br>        modifier = Modifier<br>            .width(330.dp)<br>            .height(480.dp)<br>            .padding(horizontal = 24.dp)<br>            .blur(<br>                blurRadiusSpec = BlurRadiusSpec.verticalGradient(<br>                    stops = listOf(<br>                        BlurStop(fraction = 0.00f, radius = 18.dp), // Heavily blurred top edge<br>                        BlurStop(fraction = 0.24f, radius = 8.dp), // Soft upper transition<br>                        BlurStop(fraction = 0.42f, radius = 0.dp), // Sharp center focus starts<br>                        BlurStop(fraction = 0.58f, radius = 0.dp), // Sharp center focus ends<br>                        BlurStop(fraction = 0.76f, radius = 8.dp), // Soft lower transition<br>                        BlurStop(fraction = 1.00f, radius = 18.dp), // Heavily blurred bottom edge<br>                    ),<br>                ),<br>                edgeTreatment = BlurredEdgeTreatment.Unbounded,<br>            ),<br>        contentPadding = PaddingValues(vertical = 36.dp),<br>        verticalArrangement = Arrangement.spacedBy(26.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>    ) {<br>        // ...<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*np0GYoYEv5DFdvCGNjnFsg.gif" /><figcaption><em>A vertical list of song lyric text lines where top and bottom lines fade out in blur while the center line is clear.</em></figcaption></figure><h3>Fade left and right edges of a horizontal control</h3><p>Similarly, to draw focus to the center of a horizontally scrollable or draggable component, such as a wheel picker, carousel, or measurement scale, apply BlurRadiusSpec.horizontalGradient with BlurStop entries. In the following draggable weight scale, the left and right edges soften while the ticks and numbers near the center indicator needle stay completely sharp:</p><pre>@Composable<br>fun HorizontalScaleBlurExample() {<br>    var selectedValue by remember { mutableFloatStateOf(65.0f) }<br>    val animatedValue by animateFloatAsState(<br>        targetValue = selectedValue,<br>        animationSpec = tween(durationMillis = 900, easing = FastOutSlowInEasing),<br>        label = &quot;horizontalScaleSmoothScroll&quot;,<br>    )<br>    Column(<br>        modifier = Modifier<br>            .width(340.dp)<br>            .background(Color(0xFF0F172A), RoundedCornerShape(24.dp))<br>            .padding(vertical = 24.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>    ) {<br>        Text(<br>            text = &quot;${(animatedValue * 10).roundToInt() / 10.0} kg&quot;,<br>            color = Color.White,<br>            fontSize = 44.sp,<br>            fontWeight = FontWeight.Black,<br>        )<br>        Spacer(Modifier.height(16.dp))<br>        Box(<br>            // ...<br>        ) {<br>            // Ruler ticks blurred at the left and right edges, sharp at center<br>            Canvas(<br>                modifier = Modifier<br>                    .fillMaxSize()<br>                    .blur(<br>                        blurRadiusSpec = BlurRadiusSpec.horizontalGradient(<br>                            stops = listOf(<br>                                BlurStop(fraction = 0.00f, radius = 14.dp),<br>                                BlurStop(fraction = 0.28f, radius = 0.dp),<br>                                BlurStop(fraction = 0.72f, radius = 0.dp),<br>                                BlurStop(fraction = 1.00f, radius = 14.dp),<br>                            ),<br>                        ),<br>                        edgeTreatment = BlurredEdgeTreatment.Unbounded,<br>                    ),<br>            ) {<br>                // Draw horizontal ruler ticks offset by `animatedValue`<br>                // ...<br>            }<br>            // ...<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Pmp3e1FS_VUuC12MM2V_ew.gif" /><figcaption><em>A horizontal ruler scale widget showing blurred tick marks near the edges and sharp ticks near the indicator needle.</em></figcaption></figure><h3>Create a diagonal blur with linearGradient</h3><p>BlurRadiusSpec.linearGradient varies the blur radius along a line segment between start and end DpOffset values in the layer&#39;s coordinate space. Inside the Modifier.blur lambda block, you can read BlurScope.size to run a diagonal progressive blur across a hero image from the top-left corner to the bottom-right corner, keeping the subject at the top-left completely sharp while progressively blurring the lower-right region behind the overlaid text:</p><pre>@Composable<br>fun DiagonalLinearBlurCardExample() {<br>    Box(<br>        modifier = Modifier<br>            .wrapContentSize()<br>            .background(Color(0xFFF8FAFC))<br>            .padding(10.dp),<br>    ) {<br>        Image(<br>            painter = painterResource(id = R.drawable.dog),<br>            contentDescription = stringResource(id = R.string.dog_content_description),<br>            contentScale = ContentScale.Crop,<br>            modifier = Modifier<br>                .size(width = 300.dp, height = 380.dp)<br>                .blur {<br>                    blurRadiusSpec = BlurRadiusSpec.linearGradient(<br>                        start = DpOffset(0.dp, 0.dp),<br>                        end = DpOffset(size.width, size.height),<br>                        stops = listOf(<br>                            BlurStop(fraction = 0.00f, radius = 0.dp),<br>                            BlurStop(fraction = 0.50f, radius = 0.dp),<br>                            BlurStop(fraction = 0.75f, radius = 14.dp),<br>                            BlurStop(fraction = 1.00f, radius = 28.dp),<br>                        ),<br>                    )<br>                    edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(24.dp))<br>                },<br>        )<br>        // ...<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NP58qP50U9w6Fvfu.png" /><figcaption><em>A dog portrait that is sharp in the upper-left and progressively blurred toward the lower-right corner, with sharp white title and subtitle text overlaid on the blurred region.</em></figcaption></figure><h3>Create a focus spotlight with radialGradient</h3><p>BlurRadiusSpec.radialGradient creates a circular spotlight effect by varying the blur radius outward from a focal point. Define center as a DpOffset and fallOffRadius as the Dp distance from center at which endRadius is reached. If you leave center as DpOffset.Unspecified, the gradient is centered on the composable, and if you leave fallOffRadius as Dp.Unspecified, it defaults to half of the layer&#39;s smaller dimension.</p><p>For example, applying BlurRadiusSpec.radialGradient over a passage of text and updating center from pointer drag events lets the user drag a circular reading spotlight across the paragraph while blurring the surrounding text, as shown in the following example:</p><pre>@Composable<br>fun RadialSpotlightTextExample() {<br>    var touchOffset by remember { mutableStateOf(Offset.Unspecified) }<br>    Box(<br>        modifier = Modifier<br>            .size(width = 330.dp, height = 340.dp)<br>            .background(Color(0xFF0F172A), RoundedCornerShape(20.dp))<br>            .pointerInput(Unit) {<br>                detectDragGestures(<br>                    onDragStart = { offset -&gt; touchOffset = offset },<br>                    onDrag = { change, _ -&gt; touchOffset = change.position },<br>                )<br>            }<br>            .blur {<br>                val spotlightCenter = if (touchOffset.isSpecified) {<br>                    DpOffset(touchOffset.x.toDp(), touchOffset.y.toDp())<br>                } else {<br>                    DpOffset(x = size.width / 2, y = size.height / 2)<br>                }<br>                blurRadiusSpec = BlurRadiusSpec.radialGradient(<br>                    startRadius = 0.dp,<br>                    endRadius = 10.dp,<br>                    center = spotlightCenter,<br>                    fallOffRadius = 215.dp,<br>                )<br>                edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(20.dp))<br>            }<br>            .padding(22.dp),<br>    ) {<br>        // ...<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*QDaOMWboMGNYj3jJ1mG9IA.gif" /><figcaption><em>A paragraph of text with a circular area of sharp text around the pointer that becomes progressively blurred toward the edge of the circle.</em></figcaption></figure><h3>Create a custom blur mask with a shader</h3><p>For complex spatial blur distributions beyond linear or radial gradients, such as repeating patterns, arbitrary shapes, or procedural noise, pass a custom Shader, such as an <strong>AGSL RuntimeShader</strong>, to BlurRadiusSpec.shader. The shader evaluates in layer pixel coordinates from the top-left origin, and its sampled alpha channel (0..1)scales maxRadius.</p><p>Create the shader and BlurRadiusSpec.shader configuration once using the remember composable function, so a single instance is reused across recompositions. Compose invokes the configuration block with the layer size on each resolve, which is where you set size-dependent uniforms:</p><pre>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>@Composable<br>fun ShaderBlurExample() {<br>    // Creates 6 diagonal frosted-glass bands across the image.<br>    val maskShader = remember {<br>        RuntimeShader(<br>            &quot;&quot;&quot;<br>            uniform float2 size;<br>            half4 main(float2 coord) {<br>                float2 uv = coord / size;<br>                float band = smoothstep(0.4, 0.6, fract((uv.x + uv.y) * 3.0));<br>                return half4(0.0, 0.0, 0.0, half(band));<br>            }<br>            &quot;&quot;&quot;.trimIndent(),<br>        )<br>    }<br>    val maskBlurSpec = remember(maskShader) {<br>        BlurRadiusSpec.shader(maxRadius = 24.dp) { sizePx -&gt;<br>            maskShader.setFloatUniform(&quot;size&quot;, sizePx.width, sizePx.height)<br>            maskShader<br>        }<br>    }<br>    Image(<br>        painter = painterResource(id = R.drawable.dog),<br>        contentDescription = stringResource(id = R.string.dog_content_description),<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .size(150.dp)<br>            .blur(blurRadiusSpec = maskBlurSpec),<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*bql-n-FaY6AuJ5qp.png" /><figcaption><em>A dog image with diagonal frosted-glass blur bands driven by a custom shader mask.</em></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5667a4434396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean, Scalable State Management in React: A Practical Look at Zustand and TypeScript]]></title>
            <link>https://medium.com/@irsathkareem/clean-scalable-state-management-in-react-a-practical-look-at-zustand-and-typescript-d9ec200fa6d3?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ec200fa6d3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 02:39:18 GMT</pubDate>
            <atom:updated>2026-10-16T02:39:18.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xp6js87tv22urVIWpmarpw.png" /><figcaption>State Management in React (clean &amp; scalable) with Zustand</figcaption></figure><p>For years, state management in React has swung between two extremes: over-engineering with layers of boilerplate, or under-engineering with prop-drilling and bloated context providers.</p><p>Libraries like Redux historically required action types, action creators, reducers, and provider wrappers. React’s built-in Context API, while lightweight, often brings subtle performance traps — triggering re-renders across all consumers whenever any slice of context changes.</p><p><strong>Zustand</strong> bridges this gap. It provides a simple, hook-based API that lives entirely outside the React component tree while delivering granular subscription control and first-class TypeScript support.</p><p>Let’s break down a practical implementation managing independent state slices in a single store using TypeScript and shallow selectors.</p><h3>1. Defining the Store Contract</h3><p>One of Zustand’s strongest traits with TypeScript is how naturally store interfaces map to regular JavaScript objects. You define both the state variables and their updater actions in a single interface:</p><pre>import { create } from &#39;zustand&#39;;<br>import { useShallow } from &#39;zustand/shallow&#39;;<br><br>interface CounterStore {<br>  count1: number;<br>  incC1: () =&gt; void;<br>  decC1: () =&gt; void;<br>  resetC1: () =&gt; void;<br>  setExactC1: (c: number) =&gt; void;<br>  <br>  count2: number;<br>  incC2: () =&gt; void;<br>  decC2: () =&gt; void;<br>  resetC2: () =&gt; void;<br>  setExactC2: (c: number) =&gt; void;<br>}</pre><p>By colocating state values (count1, count2) with their corresponding actions (incC1, setExactC1), your store serves as a self-documenting module.</p><h3>2. Implementing State and Actions with create()</h3><p>Zustand creates a custom React hook using the create factory. The set function handles merging updates into the state:</p><pre>const useCounterStore = create&lt;CounterStore&gt;((set, get) =&gt; ({<br>  count1: 1,<br>  incC1: () =&gt; set((state) =&gt; ({ count1: state.count1 + 1 })),<br>  decC1: () =&gt; set((state) =&gt; ({ count1: state.count1 - 1 })),<br>  resetC1: () =&gt; set({ count1: 0 }),<br>  setExactC1: (c) =&gt; set({ count1: c }),<br>  <br>  count2: 1,<br>  incC2: () =&gt; set((state) =&gt; ({ count2: state.count2 + 1 })),<br>  decC2: () =&gt; set((state) =&gt; ({ count2: state.count2 - 1 })),<br>  resetC2: () =&gt; set({ count2: 0 }),<br>  setExactC2: (c) =&gt; set({ count2: c }),<br>}));</pre><h3>Key Takeaways from the Store Implementation:</h3><ul><li><strong>Functional Updates</strong>: When an update depends on previous values, set((state) =&gt; ({ ... })) ensures access to the freshest snapshot without race conditions.</li><li><strong>Direct Value Replacement</strong>: Actions like resetC1 or setExactC1 pass object literals directly to set, automatically performing a shallow merge.</li><li><strong>No Provider Required</strong>: Because the store lives outside React’s render lifecycle, you don’t need to wrap your component tree in a &lt;Provider&gt;.</li></ul><h3>3. Subscribing in Components: Performance and Granularity</h3><p>A common pitfall with global state is subscribing to more state than a component needs, which causes unnecessary re-renders. Zustand handles this through <strong>selector functions</strong>.</p><h3>Multi-Property Extraction with useShallow</h3><p>When a component needs multiple values simultaneously, returning a new object literal inside a selector causes React to see a new reference on every render, triggering redundant updates.</p><p>Zustand solves this with useShallow:</p><pre>const { count1, count2 } = useCounterStore(<br>  useShallow((state) =&gt; ({<br>    count1: state.count1,<br>    count2: state.count2,<br>  }))<br>);</pre><p>useShallow performs a shallow equality check across the properties of the returned object. If neither count1 nor count2 has changed, the component skips re-rendering—even if another store value or action updates.</p><h3>Granular Action Subscriptions</h3><p>Because actions in Zustand are stable function references, subscribing to them directly via selectors ensures zero extraneous re-renders:</p><pre>const incC1 = useCounterStore((state) =&gt; state.incC1);<br>const decC1 = useCounterStore((state) =&gt; state.decC1);<br>const resetC1 = useCounterStore((state) =&gt; state.resetC1);<br>const setExactC1 = useCounterStore((state) =&gt; state.setExactC1);<br>const incC2 = useCounterStore((state) =&gt; state.incC2);<br>const decC2 = useCounterStore((state) =&gt; state.decC2);<br>const resetC2 = useCounterStore((state) =&gt; state.resetC2);<br>const setExactC2 = useCounterStore((state) =&gt; state.setExactC2);</pre><h3>4. Bringing It Together in the UI</h3><p>Here is the complete component consuming the store:</p><pre>const CounterComponent = () =&gt; {<br>  const { count1, count2 } = useCounterStore(<br>    useShallow((state) =&gt; ({ count1: state.count1, count2: state.count2 }))<br>  );<br><br>  const incC1 = useCounterStore((state) =&gt; state.incC1);<br>  const incC2 = useCounterStore((state) =&gt; state.incC2);<br>  const decC1 = useCounterStore((state) =&gt; state.decC1);<br>  const decC2 = useCounterStore((state) =&gt; state.decC2);<br>  const resetC1 = useCounterStore((state) =&gt; state.resetC1);<br>  const resetC2 = useCounterStore((state) =&gt; state.resetC2);<br>  const setExactC1 = useCounterStore((state) =&gt; state.setExactC1);<br>  const setExactC2 = useCounterStore((state) =&gt; state.setExactC2);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count 1: {count1}&lt;/p&gt;<br>      &lt;p&gt;Count 2: {count2}&lt;/p&gt;<br>      <br>      &lt;div className=&quot;flex&quot;&gt;<br>        &lt;button onClick={incC1}&gt;Increment Count 1&lt;/button&gt;<br>        &lt;button onClick={decC1}&gt;Decrement Count 1&lt;/button&gt;<br>        &lt;button onClick={resetC1}&gt;Reset Count 1&lt;/button&gt;<br>        &lt;button onClick={() =&gt; setExactC1(1000)}&gt;Count1 = 1000&lt;/button&gt;<br>      &lt;/div&gt;<br>      <br>      &lt;div className=&quot;flex&quot;&gt;<br>        &lt;button onClick={incC2}&gt;Increment Count 2&lt;/button&gt;<br>        &lt;button onClick={decC2}&gt;Decrement Count 2&lt;/button&gt;<br>        &lt;button onClick={resetC2}&gt;Reset Count 2&lt;/button&gt;<br>        &lt;button onClick={() =&gt; setExactC2(1000)}&gt;Count2 = 1000&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Why This Pattern Works</h3><ol><li><strong>Zero Context Overhead</strong>: No context providers, wrapper hell, or awkward dependency arrays.</li><li><strong>Explicit Contracts</strong>: TypeScript surfaces exact autocomplete and type validation for state updates and parameters (e.g., setExactC1(c: number)).</li><li><strong>Surgical Re-renders</strong>: Components only re-render when the exact slices of state they read undergo real value changes.</li></ol><p>Whether you are building isolated widgets or scaling application-wide dashboards, combining Zustand’s selector model with useShallow keeps your code maintainable, predictable, and fast.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ec200fa6d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metaball / Gooey Effect in Jetpack Compose using RenderEffect]]></title>
            <link>https://medium.com/@irsathkareem/metaball-gooey-effect-in-jetpack-compose-using-rendereffect-97919d30948d?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/97919d30948d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[render-effect]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Sat, 30 May 2026 05:19:35 GMT</pubDate>
            <atom:updated>2026-05-30T05:19:35.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWi_3X-maMcVwrD9inMmdg.png" /><figcaption>Metaball / Gooey Effect in Jetpack Compose</figcaption></figure><h3>Introduction</h3><p>Fluid, organic animations have become a popular way to make user interfaces feel more dynamic and engaging. One of the most visually appealing examples is the <strong>metaball</strong>, or <strong>gooey</strong>, effect — an animation where separate shapes appear to merge into a single liquid-like blob when they come close together and smoothly separate again as they move apart.</p><p>This effect has been widely used in loading indicators, floating action menus, music visualizers, onboarding screens, and experimental UI designs because it creates a sense of continuity and physicality that traditional animations often lack. While metaball effects have historically been implemented using SVG filters, custom shaders, or complex graphics pipelines, modern Android development provides a much simpler approach.</p><p>With the introduction of <strong>RenderEffect</strong> in Android 12 and the declarative UI model of <strong>Jetpack Compose</strong>, developers can create convincing gooey animations using a combination of blur processing and alpha-channel manipulation. By blurring multiple shapes and then applying an alpha threshold through a color matrix, individual elements can visually blend together, producing the illusion of liquid behavior without requiring custom OpenGL or shader code.</p><p>In this article, we’ll explore how a metaball effect works, why the combination of blur and alpha thresholding creates the characteristic gooey appearance, and how to implement the effect in Jetpack Compose using RenderEffect and ColorMatrix transformations. Along the way, we&#39;ll break down the rendering pipeline and examine the role each component plays in creating smooth, fluid interactions.</p><figure><img alt="Metaball Effect using Jetpack Compose" src="https://cdn-images-1.medium.com/max/400/1*AsNEWgP8ffwcbqWHmENf0Q.gif" /><figcaption>Metaball Effect</figcaption></figure><pre>@Composable<br>@Preview<br>fun FindRenderEffectPreview() {<br><br>    val infiniteTransition = rememberInfiniteTransition()<br><br>    val paddingPercentage by infiniteTransition.animateFloat(<br>        initialValue = 0f,<br>        targetValue = 1f,<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(3000),<br>            repeatMode = RepeatMode.Reverse<br>        )<br>    )<br><br>    val blur = 80f<br>    val alpha = 50f<br>    val alphaConstant = -5000f<br><br>    val renderEffect = remember {<br>        provideRenderEffect(blur, alpha, alphaConstant)<br>    }<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .then(<br>                if(renderEffect != null) {<br>                    Modifier<br>                        .graphicsLayer {<br>                            this.renderEffect = renderEffect<br>                        }<br>                } else Modifier<br>            )<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .fillMaxSize(),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            Box(<br>                modifier = Modifier<br>                    .padding(<br>                        paddingValues = PaddingValues(<br>                            bottom = (180f * paddingPercentage).dp<br>                        )<br>                    )<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br><br>            Box(<br>                modifier = Modifier<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br><br>            Box(<br>                modifier = Modifier<br>                    .padding(<br>                        paddingValues = PaddingValues(<br>                            top = (180f * paddingPercentage).dp<br>                        )<br>                    )<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br>        }<br>    }<br>}</pre><h4>Applying the Effect to the Entire Layer</h4><p>The effect is attached to the root container:</p><pre>Modifier.graphicsLayer {<br>    renderEffect = renderEffect<br>}</pre><p>This is important.</p><p>Applying the effect to each circle individually would blur them independently.</p><p>Applying it to the parent layer allows all circles to participate in the same blur pass, enabling the alpha values to merge.</p><p>Without a shared layer, there is no metaball effect.</p><pre>private fun provideRenderEffect(<br>    blurRadius: Float,<br>    alpha: Float,<br>    alphaConstant: Float<br>): RenderEffect? {<br>    if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.S) return null<br><br>    val blurEffect = android.graphics.RenderEffect.createBlurEffect(<br>        blurRadius,<br>        blurRadius,<br>        Shader.TileMode.MIRROR<br>    )<br><br>    val colorFilter = ColorFilter.colorMatrix(<br>        ColorMatrix(<br>            floatArrayOf(<br>             // R, G, B, A, constant<br>                1f, 0f, 0f, 0f, 0f, // RED&#39;<br>                0f, 1f, 0f, 0f, 0f, // GREEN&#39;<br>                0f, 0f, 1f, 0f, 0f, // BLUE&#39;<br>                0f, 0f, 0f, alpha, alphaConstant // ALPHA&#39;<br>            )<br>        )<br>    ).asAndroidColorFilter()<br><br>    val colorFilterEffect = android.graphics.RenderEffect.createColorFilterEffect(colorFilter)<br><br>    return android.graphics.RenderEffect<br>        .createChainEffect(colorFilterEffect, blurEffect)<br>        .asComposeRenderEffect()<br>}</pre><h4>Creating the Gooey RenderEffect</h4><p>The core of the metaball implementation is the provideRenderEffect() function. Its responsibility is to construct a rendering pipeline that transforms a set of ordinary shapes into a liquid-like blob. This is achieved by combining two effects: a <strong>blur</strong> and an <strong>alpha threshold</strong>.</p><pre>private fun provideRenderEffect(<br>    blurRadius: Float,<br>    alpha: Float,<br>    alphaConstant: Float<br>): RenderEffect?</pre><p>The function accepts three parameters:</p><ul><li>blurRadius – Controls how much the shapes are blurred.</li><li>alpha – Multiplies the alpha channel to increase opacity contrast.</li><li>alphaConstant – Offsets the alpha value, acting as a threshold control.</li></ul><p>Since RenderEffect is only available on Android 12 (API 31) and above, the function immediately returns null for older Android versions.</p><pre>if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.S) return null</pre><h4>Step 1: Create a Blur Effect</h4><p>The first stage of the pipeline applies a Gaussian blur to the rendered content.</p><pre>val blurEffect = android.graphics.RenderEffect.createBlurEffect(<br>    blurRadius,<br>    blurRadius,<br>    Shader.TileMode.MIRROR<br>)</pre><p>This blur softens the edges of every shape within the layer.</p><p>Without blur:</p><pre>●     ●</pre><p>With blur:</p><pre>(~~~) (~~~)</pre><p>The important characteristic of a blur is that neighboring pixels begin to influence one another. When two blurred shapes move close together, their blurred regions overlap and their alpha values accumulate.</p><pre>(~~~)(~~~)</pre><p>becomes</p><pre>(~~~~~~~~)</pre><p>This overlap forms the foundation of the metaball effect.</p><h4>Step 2: Create an Alpha Threshold Using a Color Matrix</h4><p>After blurring the content, the next step is to manipulate its alpha channel.</p><pre>val colorFilter = ColorFilter.colorMatrix(<br>    ColorMatrix(<br>        floatArrayOf(<br>            1f, 0f, 0f, 0f, 0f,<br>            0f, 1f, 0f, 0f, 0f,<br>            0f, 0f, 1f, 0f, 0f,<br>            0f, 0f, 0f, alpha, alphaConstant<br>        )<br>    )<br>)</pre><p>A ColorMatrix is a 4×5 transformation matrix that modifies the RGBA components of every pixel.</p><p>The first three rows leave the color channels unchanged:</p><pre>1f, 0f, 0f, 0f, 0f<br>0f, 1f, 0f, 0f, 0f<br>0f, 0f, 1f, 0f, 0f</pre><p>These rows effectively mean:</p><pre>R&#39; = R<br>G&#39; = G<br>B&#39; = B</pre><p>Only the alpha channel is transformed:</p><pre>0f, 0f, 0f, alpha, alphaConstant</pre><p>Which corresponds to:</p><pre>A&#39; = A × alpha + alphaConstant</pre><p>This formula dramatically increases the contrast between weak and strong alpha values.</p><p>For example:</p><pre>alpha = 50f<br>alphaConstant = -5000f</pre><p>causes:</p><ul><li>Low alpha values to become fully transparent.</li><li>High alpha values to become fully opaque.</li></ul><p>Instead of a smooth blur, the output starts behaving like a mask with sharply defined edges.</p><h4>Why This Creates the Gooey Appearance</h4><p>The blur stage generates soft overlapping regions between nearby shapes. Those overlapping areas naturally contain higher alpha values than the surrounding blur.</p><p>The alpha transformation then amplifies this difference.</p><pre>Blurred Output<br>    (~~~~~~~~)<br>Alpha Threshold<br>   ██████████</pre><p>As a result, overlapping blurred regions survive the threshold operation and appear as a solid connection between shapes.</p><p>To the viewer, it looks as though the circles have merged into a single liquid mass.</p><h4>Step 3: Convert the Color Matrix into a RenderEffect</h4><p>The color matrix is converted into a color filter and then wrapped in a RenderEffect.</p><pre>val colorFilterEffect =<br>    android.graphics.RenderEffect.createColorFilterEffect(<br>        colorFilter<br>    )</pre><p>At this point, the application has two independent effects:</p><ol><li>A blur effect.</li><li>An alpha-threshold effect.</li></ol><h4>Step 4: Chain the Effects Together</h4><p>Finally, both effects are combined into a single rendering pipeline.</p><pre>return android.graphics.RenderEffect<br>    .createChainEffect(<br>        colorFilterEffect,<br>        blurEffect<br>    )<br>    .asComposeRenderEffect()</pre><p>The processing order is:</p><pre>Original Content<br>        ↓<br>     Blur<br>        ↓<br> Alpha Threshold<br>        ↓<br>   Final Output</pre><p>This order is crucial. The content must be blurred first so that neighboring shapes can influence one another. The alpha threshold is then applied to convert the blurred overlap into a solid, connected region.</p><p>The resulting RenderEffect can be attached to a Compose graphicsLayer, allowing multiple independent shapes to visually merge and separate, producing the characteristic metaball or gooey effect.</p><h3>Alternative Methods</h3><pre>internal fun provideColorFilter(<br>    alpha: Float,<br>    alphaConstant: Float<br>) = ColorFilter.colorMatrix(<br>    ColorMatrix(<br>        floatArrayOf(<br>            // R, G, B, A, constant<br>            1f, 0f, 0f, 0f, 0f, // RED&#39;<br>            0f, 1f, 0f, 0f, 0f, // GREEN&#39;<br>            0f, 0f, 1f, 0f, 0f, // BLUE&#39;<br>            0f, 0f, 0f, alpha, alphaConstant // ALPHA&#39;<br>        )<br>    )<br>)<br><br>private fun provideRenderEffect(<br>    alpha: Float,<br>    alphaConstant: Float<br>): RenderEffect? {<br>    if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.S) return null<br><br>    val colorFilter = provideColorFilter(alpha, alphaConstant).asAndroidColorFilter()<br>    val colorFilterEffect = android.graphics.RenderEffect.createColorFilterEffect(colorFilter)<br><br>    return colorFilterEffect.asComposeRenderEffect()<br>}<br><br>@Composable<br>@Preview<br>fun FindRenderEffectPreview() {<br><br>    val infiniteTransition = rememberInfiniteTransition()<br><br>    val paddingPercentage by infiniteTransition.animateFloat(<br>        initialValue = 0f,<br>        targetValue = 1f,<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(3000),<br>            repeatMode = RepeatMode.Reverse<br>        )<br>    )<br><br>    val blur = 40.dp<br>    val alpha = 50f<br>    val alphaConstant = -5000f<br><br>    val renderEffect = remember {<br>        provideRenderEffect(alpha, alphaConstant)<br>    }<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .graphicsLayer {<br>                this.renderEffect = renderEffect<br>            }<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .fillMaxSize(),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            Box(<br>                modifier = Modifier<br>                    .padding(<br>                        paddingValues = PaddingValues(<br>                            bottom = (180f * paddingPercentage).dp<br>                        )<br>                    )<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .blur(blur, BlurredEdgeTreatment.Unbounded)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br><br>            Box(<br>                modifier = Modifier<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .blur(blur, BlurredEdgeTreatment.Unbounded)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br><br>            Box(<br>                modifier = Modifier<br>                    .padding(<br>                        paddingValues = PaddingValues(<br>                            top = (180f * paddingPercentage).dp<br>                        )<br>                    )<br>                    .size(50.dp)<br>                    .clip(CircleShape)<br>                    .blur(blur, BlurredEdgeTreatment.Unbounded)<br>                    .background(Color(0.306f, 0.541f, 0.945f, 1.0f))<br>            )<br>        }<br>    }<br>}</pre><p>Backward Compatibility</p><pre><br><br>// Fake Alpha threshold<br>class ColorMatrixModifier(val matrix: ColorMatrix): DrawModifier {<br>    override fun ContentDrawScope.draw() {<br>        val paint = Paint().apply {<br>            colorFilter = ColorFilter.colorMatrix(matrix)<br>        }<br>        drawIntoCanvas { canvas -&gt;<br>            canvas.saveLayer(bounds = size.toRect(), paint) // Offscreen buffer<br>            drawContent() // Draw Child<br>            canvas.restore() // matrix applied to combined result<br>        }<br>    }<br>}<br><br>// Fake Blur<br>fun Modifier.outlineGradientBlur(<br>    color: Color,<br>    gradientRadiusOffset: Dp<br>) = this.then(<br>    Modifier.drawWithCache {<br>        val innerRadius = size.minDimension / 2<br>        val outerRadius = innerRadius + gradientRadiusOffset.toPx()<br>        val center = Offset(size.width / 2, size.height / 2)<br><br>        val blur = Brush.radialGradient(<br>            colorStops = arrayOf(<br>                0f to color.copy(alpha = 0f), // may be alpha=1f<br>                (innerRadius / outerRadius) to color,<br>                1f to color.copy(alpha = 0f)<br>            ),<br>            center = center,<br>            radius = outerRadius<br>        )<br><br>        onDrawWithContent {<br>            drawCircle(<br>                brush = blur,<br>                radius = outerRadius,<br>                center = center<br>            )<br>            drawContent()<br>        }<br>    }<br>)<br><br>@Composable<br>fun MetaballTest() {<br>    val metaBallColorMatrix = ColorMatrix() // provideColorMatrix(alpha, alphaConstant)<br>    val color = Color(Random.nextFloat(), Random.nextFloat(), Random.nextFloat(), 1f)<br>    <br>    // API 21+<br>    Box(<br>        Modifier.then(ColorMatrixModifier(metaBallColorMatrix))<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .outlineGradientBlur(color, 36.dp)<br>                .background(color, CircleShape)<br>        )<br>        Box(<br>            modifier = Modifier<br>                .outlineGradientBlur(color, 36.dp)<br>                .background(color, CircleShape)<br>        )<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97919d30948d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Particle Emitters using Jetpack Compose — Physics simulation using TargetBasedAnimation<T>]]></title>
            <link>https://medium.com/@irsathkareem/particle-emitters-using-jetpack-compose-physics-simulation-using-targetbasedanimation-t-5c67083a23cf?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c67083a23cf</guid>
            <category><![CDATA[physics-simulation]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-animation]]></category>
            <category><![CDATA[particle-effect]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Wed, 27 May 2026 06:37:27 GMT</pubDate>
            <atom:updated>2026-09-04T15:37:34.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wa-JCo1Kbju2rZXOqYy8fw.png" /><figcaption>Thumbnail Image</figcaption></figure><p>Modern user interfaces are no longer limited to static layouts and simple transitions. From celebratory confetti effects to floating particles, sparks, smoke, and interactive visual feedback, motion has become an essential part of creating engaging user experiences. In Android development, these effects are often associated with game engines or specialized graphics frameworks, but Jetpack Compose provides powerful animation APIs that make sophisticated motion systems surprisingly accessible.</p><p>One particularly interesting approach is building particle systems using physics-based animations. Instead of manually calculating every frame, developers can leverage Compose’s animation engine to model realistic movement, acceleration, velocity, and decay. This allows particles to behave more naturally, producing effects that feel dynamic and responsive while remaining declarative and composable.</p><p>In this article, we’ll explore how to create particle emitters in Jetpack Compose using TargetBasedAnimation&lt;T&gt;. Although this API is commonly used for driving animations between states, it can also serve as the foundation for custom physics simulations. By combining animation specifications with particle lifecycle management, we can create visually rich effects that are both efficient and highly customizable.</p><p>Whether you’re building celebratory animations, interactive UI feedback, or experimental visual experiences, understanding how TargetBasedAnimation&lt;T&gt; can power a particle system opens up a new set of possibilities within the Compose ecosystem. By the end of this article, you&#39;ll have a clear understanding of how to design, animate, and render particle emitters using Compose&#39;s animation infrastructure while maintaining the declarative principles that make Jetpack Compose so powerful.</p><p>In this article, we’ll build a fully functional particle emitter using Jetpack Compose and TargetBasedAnimation&lt;T&gt;. The emitter continuously generates particles, animates them across randomized trajectories, gradually fades them out, and automatically removes them when their animations complete. We&#39;ll also make the emitter interactive by attaching it to a draggable composable, allowing particles to be emitted from a moving source in real time.</p><pre>@Preview<br>@Composable<br>private fun ParticleEmitterPreview() {<br>    Box(<br>        modifier = Modifier.fillMaxSize(),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        ParticleEmitter()<br>    }<br>}</pre><figure><img alt="Particle Emitter Animation Preview in Jetpack Compose" src="https://cdn-images-1.medium.com/max/400/1*5LZF49RuL2R04pUHMhoa0A.gif" /><figcaption>ParticleEmitterPreview</figcaption></figure><p>The implementation demonstrates several advanced Compose concepts working together:</p><ul><li>Frame-synchronized updates using withFrameNanos</li><li>Continuous particle emission with produceState</li><li>Manual animation evaluation using TargetBasedAnimation&lt;T&gt;</li><li>Custom drawing with drawBehind</li><li>Particle lifecycle management</li><li>Interactive particle sources using draggable2D</li></ul><p>The final result is a lightweight particle engine capable of rendering hundreds of animated particles while remaining entirely within the Compose runtime.</p><pre><br>class Particle(<br>    private val start: Offset,<br>    private val end: Offset,<br>    private val startTimeNanos: Long,<br>    val color: Color = Color.RandomColor<br>) {<br>    private val id = UUID.randomUUID().toString()<br>    private val animationProgress = TargetBasedAnimation(<br>        initialValue = 0f,<br>        targetValue = 1f,<br>        typeConverter = Float.VectorConverter,<br>        animationSpec = tween(700)<br>    )<br><br>    private val _position = mutableStateOf(Offset.Unspecified)<br>    val position: State&lt;Offset&gt; = _position<br><br>    private val _alpha = mutableFloatStateOf(1f)<br>    val alpha: State&lt;Float&gt; = _alpha<br><br>    // Game Loop (called on every frame)<br>    // Best place to drive physics of this particle<br>    fun updateLoop(frameTime: Long): Boolean {<br>        if(isFinished(frameTime)) return false<br>        _position.value = positionAt(frameTime)<br>        _alpha.floatValue = alphaAt(frameTime)<br>        return true<br>    }<br><br>    private fun positionAt(playTimeNanos: Long): Offset = lerp(start, end, animationPercentage(playTimeNanos))<br>    private fun alphaAt(playTimeNanos: Long): Float = lerp(1f, 0f, animationPercentage(playTimeNanos))<br><br>    private fun animationPercentage(playTimeNanos: Long): Float = animationProgress.getValueFromNanos(elapsedFrom(playTimeNanos))<br>    private fun isFinished(playTimeNanos: Long) = animationProgress.isFinishedFromNanos(elapsedFrom(playTimeNanos))<br><br>    private fun elapsedFrom(playTimeNanos: Long) = playTimeNanos - startTimeNanos<br><br>    override fun equals(other: Any?): Boolean {<br>        if (this === other) return true<br>        if (javaClass != other?.javaClass) return false<br><br>        other as Particle<br><br>        if (id != other.id) return false<br>        if (startTimeNanos != other.startTimeNanos) return false<br><br>        return true<br>    }<br><br>    override fun hashCode(): Int {<br>        var result = startTimeNanos.hashCode()<br>        result = 31 * result + id.hashCode()<br>        return result<br>    }<br>}</pre><h4>Modeling a Particle with TargetBasedAnimation</h4><p>The Particle class represents a single particle within our simulation. Every emitted particle owns its own state, lifecycle, animation timeline, and visual properties. While the emitter is responsible for creating particles and rendering them, the particle itself is responsible for answering a much more important question:</p><blockquote>“Given the current frame time, where should I be and what should I look like?”</blockquote><p>This is where TargetBasedAnimation becomes the foundation of the entire system.</p><pre>class Particle(<br>    private val start: Offset,<br>    private val end: Offset,<br>    private val startTimeNanos: Long,<br>    val color: Color = Color.RandomColor<br>)</pre><p>Each particle is initialized with:</p><ul><li>A starting position</li><li>A destination position</li><li>The timestamp when it was created</li><li>A randomly generated color</li></ul><p>Together, these values define the particle’s journey through the simulation.</p><p><strong>Using </strong><strong>TargetBasedAnimation as a Timeline</strong></p><p>At the heart of the particle is a TargetBasedAnimation.</p><pre>private val animationProgress = TargetBasedAnimation(<br>    initialValue = 0f,<br>    targetValue = 1f,<br>    typeConverter = Float.VectorConverter,<br>    animationSpec = tween(700)<br>)</pre><p>This animation doesn’t directly animate a UI property.</p><p>Instead, it acts as a normalized timeline that progresses from 0f to 1f over 700 milliseconds.</p><p>Think of it as a reusable progress generator:</p><p>TimeProgress [Start-0.0] [Midway-0.5] [End-1.0]</p><p>The particle can then use this progress value to drive multiple properties simultaneously.</p><p>This is a key distinction from higher-level animation APIs such as animateFloatAsState. Rather than Compose automatically updating values for us, we&#39;re manually querying the animation at any point in time.</p><h4><strong>Evaluating Animation State Manually</strong></h4><p>Unlike typical Compose animations, we never start this animation.</p><p>Instead, we continuously ask:</p><blockquote>“What would the animation value be at this timestamp?”</blockquote><pre>animationProgress.getValueFromNanos(...)</pre><p>This is one of the most powerful capabilities of TargetBasedAnimation.</p><p>Because the animation is deterministic, we can evaluate it at any moment without maintaining an animation coroutine or transition state.</p><p>The particle effectively becomes a mathematical function:</p><pre>time → animation progress</pre><p>This approach scales extremely well because hundreds of particles can independently calculate their state from the same animation definition.</p><h4>Updating the Particle Each Frame</h4><p>Whenever a frame is rendered, the particle receives the current frame timestamp.</p><pre>fun updateLoop(frameTime: Long): Boolean</pre><p>The particle then:</p><ol><li>Determines whether its animation has completed</li><li>Calculates its current position</li><li>Calculates its current opacity</li><li>Updates its observable state</li></ol><p>If the animation is finished, the particle signals that it should be removed from the simulation.</p><pre>if (isFinished(frameTime)) return false</pre><p>This creates a self-contained lifecycle where particles automatically expire once their animation reaches the end.</p><p><strong><em>Position as a Function of Progress</em></strong></p><p>Movement is derived from the animation progress.</p><pre>private fun positionAt(playTimeNanos: Long): Offset =<br>    lerp(start, end, animationPercentage(playTimeNanos))</pre><p>Here, lerp (linear interpolation) computes a position somewhere between the start and end points.</p><p>When progress is:</p><ul><li>0f → particle is at the start</li><li>0.5f → particle is halfway</li><li>1f → particle reaches the destination</li></ul><p>Because the animation timeline already handles easing and duration, position calculation becomes trivial.</p><p>The particle doesn’t need velocity calculations or manual coordinate updates. It simply asks the animation how far along it should be.</p><p><strong><em>Opacity Uses the Same Timeline</em></strong></p><p>The same animation progress drives transparency.</p><pre>private fun alphaAt(playTimeNanos: Long): Float =<br>    lerp(1f, 0f, animationPercentage(playTimeNanos))</pre><p>As progress increases:</p><pre>0.0 → alpha = 1.0<br>0.5 → alpha = 0.5<br>1.0 → alpha = 0.0</pre><p>This creates a smooth fade-out effect throughout the particle’s lifetime.</p><p>One of the elegant aspects of this design is that a single animation timeline controls multiple visual properties:</p><ul><li>Position</li><li>Opacity</li><li>Potentially scale</li><li>Potentially rotation</li><li>Potentially color transitions</li></ul><p>Everything remains synchronized because every property is derived from the same progress value.</p><h4>Time-Based Rather Than Frame-Based</h4><p>Notice that all calculations are based on timestamps.</p><pre>elapsedFrom(playTimeNanos)</pre><p>Rather than incrementing position every frame, we calculate how much time has elapsed since particle creation.</p><pre>playTimeNanos - startTimeNanos</pre><p>This makes the simulation frame-rate independent.</p><p>Whether the device renders at:</p><ul><li>60 FPS</li><li>90 FPS</li><li>120 FPS</li></ul><p>the particle will still complete its animation in exactly 700 milliseconds.</p><p>This is one of the biggest advantages of using TargetBasedAnimation as the simulation engine: timing accuracy is handled by Compose&#39;s animation system rather than manual frame counting.</p><p><strong><em>Determining When a Particle Dies</em></strong></p><p>A particle’s lifetime is tied directly to the animation.</p><pre>animationProgress.isFinishedFromNanos(...)</pre><p>Once the animation reaches its target value, the particle is considered dead and can be removed from the emitter.</p><p>This creates a very natural lifecycle:</p><pre>Created<br>    ↓<br>Animating<br>    ↓<br>Fading<br>    ↓<br>Finished<br>    ↓<br>Removed</pre><p>No additional timers or cleanup logic are required.</p><p><strong><em>Why This Approach Works So Well?</em></strong></p><p>Traditional particle systems often store mutable properties such as:</p><ul><li>Velocity</li><li>Acceleration</li><li>Age</li><li>Lifetime</li></ul><p>and update them every frame.</p><p>This implementation takes a different approach.</p><p>Instead of storing continuously changing values, we store:</p><ul><li>Initial conditions</li><li>Animation definition</li><li>Creation timestamp</li></ul><p>Everything else is derived from those inputs whenever a frame is rendered.</p><p>The result is a lightweight, deterministic particle model where TargetBasedAnimation effectively serves as a miniature physics engine. Each particle becomes a self-contained simulation that can calculate its exact state at any moment in time, making it an ideal building block for scalable particle effects in Jetpack Compose.</p><pre>@Composable<br>fun ParticleEmitter() {<br>    // Continuos emission of particles<br>    val particles by provideParticles()<br><br>    var boxPosition by remember { mutableStateOf(IntOffset.Zero) }<br><br>    Box(<br>        modifier = Modifier<br>            .size(80.dp)<br>            .offset { boxPosition }<br>            .drawBehind {<br>                withTransform(<br>                    {<br>                        translate(center.x, center.y)<br>                    },<br>                ) {<br>                    particles.forEach {<br>                        // Draw Particle<br>                        drawCircle(<br>                            color = it.color.copy(alpha = it.alpha.value),<br>                            radius = 10.dp.toPx(),<br>                            center = it.position.value<br>                        )<br>                    }<br>                }<br>            }<br>            .background(<br>                brush = Brush.radialGradient(<br>                    colors = listOf(<br>                        Color.Blue,<br>                        Color.Green,<br>                        Color.Blue<br>                    ),<br>                    tileMode = TileMode.Clamp<br>                ),<br>                shape = CircleShape<br>            )<br>            .draggable2D(<br>                rememberDraggable2DState {<br>                    boxPosition += it.round()<br>                }<br>            )<br>    )<br>}</pre><p>The ParticleEmitter composable acts as both the <strong>particle source</strong> and the <strong>rendering surface</strong> for our particle system. In traditional game engines, particle emitters are responsible for spawning particles, updating them over time, and drawing them on every frame. Here, we adopt the same concept using Compose&#39;s declarative APIs.</p><pre>@Composable<br>private fun provideParticles(): State&lt;List&lt;Particle&gt;&gt; {<br>//    val updatedStart = rememberUpdatedState(start)<br>//    val updatedEnd = rememberUpdatedState(end)<br><br>    return produceState(emptyList()) {<br>        val particles = mutableListOf&lt;Particle&gt;()<br>        val updatedStart = Offset.Zero<br><br>        var lastEmissionTime = 0L<br>        val emissionInterval = 25_000_000L // 25 ms<br><br>        while (true) {<br>            // withFrameNanos - Called on every frame is scheduled<br>            // frameTime - Exact time in nanoseconds, at which the frame is scheduled<br>            value = withFrameNanos { frameTime -&gt;<br>                val end = Offset.Random2D<br>                <br>                // Emit new particles at regular intervals<br>                while (frameTime - lastEmissionTime &gt;= emissionInterval) {<br>                    if(particles.size &lt; 250) {<br>                        particles += Particle(<br>                            start = updatedStart,<br>                            end = end,<br>                            startTimeNanos = frameTime<br>                        )<br>                    }<br>                    lastEmissionTime += emissionInterval<br>                }<br><br>                // Remove all the finished ones<br>                particles.removeAll { !it.updateLoop(frameTime) }<br><br>                particles.toList()<br>            }<br>        }<br>    }<br>}</pre><h4>Managing the Particle Simulation Loop</h4><p>So far, we’ve seen how individual particles calculate their own state using TargetBasedAnimation. The next piece of the puzzle is managing the collection of active particles and updating them over time.</p><p>This responsibility belongs to provideParticles().</p><p><strong><em>A Compose-Friendly Game Loop</em></strong></p><p>Particle systems traditionally rely on a game loop:</p><pre>Update<br>    ↓<br>Render<br>    ↓<br>Update<br>    ↓<br>Render</pre><p>Compose doesn’t expose a traditional game engine loop, but it does provide access to the rendering timeline through withFrameNanos.</p><p>Combined with produceState, we can build a simulation loop that integrates naturally with Compose&#39;s state system.</p><p>The result is a continuously updating state object that represents the current set of active particles.</p><p><strong><em>Why </em></strong><strong><em>produceState?</em></strong></p><p>The particle system is fundamentally asynchronous.</p><p>Particles are being:</p><ul><li>Created</li><li>Updated</li><li>Destroyed</li></ul><p>independently of user interactions.</p><p>produceState is an ideal fit because it allows us to continuously produce values over time while exposing them as Compose state.</p><pre>return produceState(emptyList()) { ... }</pre><p>Whenever the produced value changes, Compose automatically schedules recomposition for any consumers of that state.</p><p>This means the emitter never needs to manually request redraws. Updating the state is enough.</p><p><strong><em>Synchronizing with the Rendering Pipeline</em></strong></p><p>The most important part of the implementation is:</p><pre>withFrameNanos { frameTime -&gt; ... }</pre><p>Rather than running updates as fast as possible, we synchronize the simulation with Compose’s rendering pipeline.</p><p>For every frame:</p><ol><li>Compose schedules a frame.</li><li>withFrameNanos provides the exact timestamp.</li><li>The particle system updates itself using that timestamp.</li><li>The updated state is rendered.</li></ol><p>This keeps the simulation perfectly aligned with the UI rendering lifecycle.</p><p><strong><em>Why Frame Time Matters</em></strong></p><p>Notice that we don’t use delays or counters.</p><p>Instead, every decision is based on the frame timestamp.</p><pre>frameTime</pre><p>This timestamp becomes the single source of truth for the entire simulation.</p><p>It determines:</p><ul><li>When particles are emitted</li><li>How far each particle has progressed</li><li>Whether a particle has expired</li></ul><p>Since both emission and animation rely on the same clock, the entire system remains deterministic and frame-rate independent.</p><p><strong><em>Emitting Particles at Fixed Intervals</em></strong></p><p>The emitter continuously generates new particles.</p><pre>val emissionInterval = 25_000_000L</pre><p>This corresponds to approximately 25 milliseconds, or roughly 40 particles per second.</p><p>Rather than emitting one particle every frame, emission is time-based.</p><pre>while (frameTime - lastEmissionTime &gt;= emissionInterval)</pre><p>This distinction is important.</p><p>If a device drops frames, a frame-based emitter might accidentally emit fewer particles than intended.</p><p>A time-based emitter remains consistent because it calculates how much emission time has elapsed since the previous frame.</p><p>Even if rendering pauses briefly, the emitter can “catch up” by creating multiple particles during the next update.</p><p>This ensures a stable emission rate regardless of frame rate fluctuations.</p><p><strong><em>Randomized Particle Trajectories</em></strong></p><p>Each newly created particle receives a random destination.</p><pre>val end = Offset.Random2D</pre><p>The particle itself doesn’t know anything about randomness.</p><p>Its only responsibility is moving from:</p><pre>Start Position<br>        ↓<br>Destination Position</pre><p>By assigning randomized endpoints during creation, we create the appearance of particles exploding outward in different directions.</p><p>This separation is useful because emission logic and particle behavior remain independent concerns.</p><p><strong><em>Updating Active Particles</em></strong></p><p>Once particles exist, they must advance through their animation timelines.</p><pre>particles.removeAll {<br>    !it.updateLoop(frameTime)<br>}</pre><p>Every frame, each particle receives the current timestamp.</p><p>Internally, the particle:</p><ul><li>Queries its TargetBasedAnimation</li><li>Calculates its current position</li><li>Calculates its current opacity</li><li>Determines whether its lifetime has ended</li></ul><p>This is where the simulation and animation systems meet.</p><p>The emitter manages the collection, while each particle manages its own state.</p><p><strong><em>Automatic Lifecycle Management</em></strong></p><p>One elegant aspect of this design is that particle cleanup happens naturally.</p><p>A particle returns false when its animation has completed.</p><pre>if (isFinished(frameTime)) return false</pre><p>The emitter then removes it from the active collection.</p><p>This means particle lifetime is entirely driven by the animation timeline.</p><pre>Created<br>    ↓<br>Updated every frame<br>    ↓<br>Animation finishes<br>    ↓<br>Removed automatically</pre><p>No additional expiration logic or timers are required.</p><p>particles is maintained as a mutable list internally, but simply modifying its contents does not change the list reference. Since Compose state observes object references, assigning the same list instance may not trigger recomposition. By returning particles.toList(), we create a new list instance on every update, ensuring that the State receives a new reference and Compose correctly detects the change and redraws the particle system.</p><h4>Utility Extensions</h4><p>To make the particle system more dynamic, we use a pair of utility extensions that generate random positions and colors for newly emitted particles.</p><pre>private val Offset.Companion.Random2D: Offset get() = Random.run {<br>    val factor = 400.0<br>    Offset(<br>        x = nextDouble(-factor, factor).toFloat(),<br>        y = nextDouble(-factor, factor).toFloat(),<br>    )<br>}<br><br>private val Color.Companion.RandomColor: Color get() = Random.run {<br>    Color(<br>        red = nextFloat(),<br>        blue = nextFloat(),<br>        green = nextFloat(),<br>        alpha = 1f,<br>    )<br>}</pre><p>Random2D generates a random destination point within a two-dimensional range around the emitter. Each particle receives a different target position, causing particles to travel in various directions and creating the familiar burst-like effect commonly seen in particle systems.</p><p>Similarly, RandomColor assigns a random color to every particle at creation time. This adds visual variety to the simulation and makes the emitted particles feel more organic and lively. Since the color is generated only once during particle creation, it remains constant throughout the particle&#39;s lifetime while the alpha value is animated independently to produce the fade-out effect.</p><p>Although these utilities are small, they play an important role in making the particle system feel less mechanical and more visually engaging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c67083a23cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android: Realtime Firebase FireStore data with Kotlin coroutines and callbackFlow]]></title>
            <link>https://medium.com/@irsathkareem/android-realtime-firebase-firestore-data-with-kotlin-coroutines-and-callbackflow-0f6772d07fde?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f6772d07fde</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 15:50:14 GMT</pubDate>
            <atom:updated>2026-09-04T15:27:00.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1rqLKRjKWL-Zd9263c8lA.png" /><figcaption>Thumbnail image</figcaption></figure><p>When building modern Android applications, real-time data updates are often essential — especially when working with cloud databases like <strong>Firebase Firestore</strong>. Instead of polling for data, Firestore provides snapshot listeners that push changes to your app whenever the underlying data changes. In Kotlin, we can take this a step further by wrapping these listeners in <strong>coroutines and flows</strong>, giving us a clean, reactive API.</p><p>The code below demonstrates how to achieve this using Kotlin’s callbackFlow.</p><pre>class FirestoreClient {<br>    fun observeUsers() = callbackFlow {<br>        val db = Firebase.firestore<br><br>        val query1 = db.collection(&quot;users&quot;) // Select All<br><br>        val query2 = db.collection(&quot;users&quot;)<br>            .where(Filter.greaterThan(&quot;age&quot;,20)) // Select age &gt; 20<br>        <br>        val query = query1 // or query2<br>        <br>        val registration = query.addSnapshotListener { snapshot, exc -&gt;<br>                exc?.let {<br>                    println(&quot;Firestore Exception: ${it.message}&quot;)<br>                    it.printStackTrace()<br>                }<br><br>                val users = snapshot?.documents?.mapNotNull {<br>                    val id = it.get(&quot;id&quot;, String::class.java) ?: return@mapNotNull null<br>                    val name = it.get(&quot;name&quot;, String::class.java) ?: return@mapNotNull null<br>                    val age = it.get(&quot;age&quot;, Int::class.java) ?: return@mapNotNull null<br><br>                    User(id, name, age)<br>                }<br><br>                users?.let {<br>                    trySend(it)<br>                }<br>            }<br><br>        awaitClose { <br>            registration.remove()<br>        }<br>    }<br>}</pre><h3>Breaking Down the Code</h3><h3>1. Using callbackFlow</h3><p>The function observeUsers() returns a Flow&lt;List&lt;User&gt;&gt;. The callbackFlow builder is perfect for wrapping APIs that use callback-based listeners. It allows you to bridge the gap between Firestore’s listener and Kotlin’s flow-based reactive streams.</p><pre>fun observeUsers() = callbackFlow {<br>    // Flow body<br>}</pre><p>This makes observeUsers() a <strong>cold flow</strong>: the Firestore listener is only attached when a collector starts consuming the flow.</p><h3>2. Firestore Queries</h3><p>Inside the flow, two queries are defined:</p><pre>val query1 = db.collection(&quot;users&quot;) // Fetch all users<br>val query2 = db.collection(&quot;users&quot;)<br>    .where(Filter.greaterThan(&quot;age&quot;,20)) // Fetch users older than 20</pre><p>By switching between query1 and query2, you can control what data to observe. This pattern makes the method flexible—you could even parameterize it to accept conditions.</p><h3>3. Attaching a Snapshot Listener</h3><p>Firestore provides addSnapshotListener, which triggers whenever the data in the query changes:</p><pre>val registration = query.addSnapshotListener { snapshot, exc -&gt; ... }</pre><ul><li>If there’s an exception (exc), it is logged.</li><li>If the snapshot is valid, documents are converted into User objects.</li></ul><h3>4. Mapping Firestore Documents to a Model</h3><p>Firestore returns DocumentSnapshot objects. The code safely extracts fields and maps them into a custom data class:</p><pre>val users = snapshot?.documents?.mapNotNull {<br>    val id = it.get(&quot;id&quot;, String::class.java) ?: return@mapNotNull null<br>    val name = it.get(&quot;name&quot;, String::class.java) ?: return@mapNotNull null<br>    val age = it.get(&quot;age&quot;, Int::class.java) ?: return@mapNotNull null<br><br>    User(id, name, age)<br>}</pre><p>Here, null-safety ensures that only fully valid documents are turned into User objects.</p><h3>5. Emitting Values into the Flow</h3><p>Once the list of users is ready, it’s sent to collectors via:</p><pre>users?.let { trySend(it) }</pre><p>trySend is non-blocking and ensures that flow collectors receive the latest list of users immediately.</p><h3>6. Cleaning Up with awaitClose</h3><p>When the collector stops observing, the listener must be removed to prevent memory leaks:</p><pre>awaitClose { <br>    registration.remove()<br>}</pre><p>This ensures the Firestore snapshot listener is properly disposed of when the flow is cancelled.</p><h3>Why This Approach is Powerful</h3><ul><li><strong>Reactive updates</strong>: Consumers of observeUsers() get a continuous stream of updates without manual refresh logic.</li><li><strong>Coroutines-friendly</strong>: Works seamlessly with Kotlin coroutines and structured concurrency.</li><li><strong>Flexibility</strong>: Easily switch or parameterize queries.</li><li><strong>Resource-safe</strong>: awaitClose ensures proper cleanup.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f6772d07fde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Maps Compose: Custom Marker Icon with dynamic images]]></title>
            <link>https://medium.com/@irsathkareem/google-maps-compose-custom-marker-icon-with-dynamic-images-df85dfa4d9d8?source=rss-8bbb0c9e3eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/df85dfa4d9d8</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[google-maps]]></category>
            <dc:creator><![CDATA[Irsath Kareem]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 16:18:14 GMT</pubDate>
            <atom:updated>2026-09-04T15:30:45.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hn1QNEt_Dhq6ochU7s5JTw.png" /><figcaption>Thumbnail image</figcaption></figure><p>In Jetpack Compose, Google Maps are the one which I want to explore more.</p><p>In that note, Today, I like to write about the concept of Custom Marker icons in Google maps</p><p>The Idea is to simulate the following:</p><p>Consider, In Social Media apps, In Group chat room, I want to show the locations of the Online users in Google maps,</p><p>It will be helpful, if the friend’s location (marker) contains the friend’s current profile picture, right.</p><p>Now, We see the implementation.</p><p>Typical Google map composable for this scenario looks like</p><pre>data class Friend(<br>  val userId: String,<br>  val displayName: String,<br>  ...<br>  val profilePictureUrl: String? = null<br>)<br><br>data class FriendWithCurrentLocation(<br>  val friend: Friend,<br>  val position: LatLng<br>)</pre><pre>@Composable fun FriendsMap(<br>  friends: List&lt;FriendWithCurrentLocation&gt;,<br>  modifier: Modifier = Modifier<br>) {<br>  val cameraPositionState = rememberCameraPositionState()<br>  <br>  GoogleMap(<br>    cameraPositionState = cameraPositionState,<br>    modifier = modifier.fillMaxSize()<br>  ) {<br>    friends.forEach { friend -&gt;<br>      Marker(state = rememberUpdatedMarkerState(position = friend.position))<br>    }<br><br>    MapEffect(friends) { map: GoogleMap<br>      val bounds = LatLngBounds.builder().run { <br>        friends.forEach { friend -&gt;<br>            include(friend.position)<br>        }<br>        build()<br>      }<br>      <br>      map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50))<br>    }<br>  }<br>}</pre><p>Above will show the default location icon as marker at all friends location.</p><p>And, One more, Map Bounds are adjusted to see all user’s at once.</p><p>Now, the important part, Below is the code to use customMarkerIcon</p><pre>@Composable<br>fun FriendsMap(<br>    friends: List&lt;FriendWithCurrentLocation&gt;,<br>    modifier: Modifier = Modifier<br>) {<br>    val cameraPositionState = rememberCameraPositionState()<br>    <br>    GoogleMap(<br>        cameraPositionState = cameraPositionState,<br>        modifier = modifier<br>    ) {<br>        val context = LocalContext.current<br><br>        data class FriendWithImageMarker(<br>            val friend: FriendWithCurrentLocation,<br>            val markerIcon: BitmapDescriptor<br>        )<br><br>        val friendsMarkers by produceState(emptyList()) {<br>            value = friends.map {<br>                FriendWithImageMarker(<br>                    friend = it,<br>                    markerIcon = customMarkerIcon(context, it.friend.profilePicUrl)<br>                )<br>            }<br>        }<br><br>        friendsMarkers.forEach { friend -&gt;<br>            Marker(<br>                state = rememberUpdatedMarkerState(position = friend.friend.position),<br>                icon = friend.markerIcon<br>            )<br>        }<br><br>        MapEffect(friends) {<br>            val bounds = LatLngBounds.builder().run {<br>                friends.forEach { friend -&gt;<br>                    include(friend.position)<br>                }<br>                build()<br>            }<br><br>            it.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50))<br>        }<br>    }<br>}</pre><p>Now, we see customMarkerIcon(…) in detail</p><pre>private suspend fun customMarkerIcon(<br>    context: Context,<br>    imageUrl: String? = null<br>): BitmapDescriptor {<br>    val drawable = fetchCustomMarkerImage(context, imageUrl, R.drawable.ic_launcher_foreground)<br><br>    val imageBitmap = (drawable as BitmapDrawable).bitmap<br><br>    val height = 300<br>    val width = height / 2<br>    val output = createBitmap(width, height) // androidx.core.graphics<br>    val canvas = Canvas(output)<br><br>    val imageSize = width<br><br>    // Location Icon Path<br>    val anchorPath = Path().apply {<br>        addArc(0f, 0f, imageSize.toFloat(), imageSize.toFloat(), 180f, 180f)<br>        moveTo(canvas.width/2f, canvas.height.toFloat())<br>        lineTo(0f, imageSize.toFloat() / 2f)<br>        lineTo(canvas.width.toFloat(), imageSize.toFloat() / 2f)<br>    }<br><br>    canvas.drawPath(anchorPath, Paint().apply {<br>        color = android.graphics.Color.BLACK<br>        style = Paint.Style.FILL<br>    })<br><br>    canvas.withClip(<br>        Path().apply { addCircle(width * .5f, width * .5f, width * .4f, Path.Direction.CW ) }<br>    ) {<br>        val scaledBitmap = imageBitmap.scale(imageSize, imageSize)<br>        // Draw Profile Picture<br>        canvas.drawBitmap(scaledBitmap, 0f, 0f, Paint().apply { isAntiAlias = true })<br>    }<br><br>    return BitmapDescriptorFactory.fromBitmap(output)<br>}</pre><pre>private suspend fun fetchCustomMarkerImage(<br>    context: Context,<br>    imageUrl: String?,<br>    @DrawableRes fallback: Int<br>): Drawable {<br>    if(imageUrl == null) return context.getDrawable(fallback)!!<br>    <br>    // Coil 3<br>    val imageRequest = ImageRequest.Builder(context)<br>        .data(imageUrl)<br>        .allowHardware(false)<br>        .build()<br><br>    val imageResult = context.imageLoader.execute(imageRequest)<br><br>    return when(imageResult) {<br>        is ErrorResult -&gt; context.getDrawable(fallback)!!<br>        is SuccessResult -&gt; imageResult.image.asDrawable(context.resources)<br>    }<br>}</pre><p>Now it shows the Marker Icon as (Location Icon with Rounded Profile picture)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df85dfa4d9d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>