<?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 Stephen Vinouze on Medium]]></title>
        <description><![CDATA[Stories by Stephen Vinouze on Medium]]></description>
        <link>https://medium.com/@s.vinouze?source=rss-c11030d62971------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SYG1h6rgqcmrYhMh.jpg</url>
            <title>Stories by Stephen Vinouze on Medium</title>
            <link>https://medium.com/@s.vinouze?source=rss-c11030d62971------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:19:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s.vinouze/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[Clustering With Maps Compose For Android]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/clustering-with-maps-compose-for-android-911a2fe3f08b?source=rss-c11030d62971------2"><img src="https://cdn-images-1.medium.com/max/2600/0*xTF-3bcxYFRpdwoL" width="6240"></a></p><p class="medium-feed-snippet">Bridging the maps-util library with Jetpack Compose</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/clustering-with-maps-compose-for-android-911a2fe3f08b?source=rss-c11030d62971------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/clustering-with-maps-compose-for-android-911a2fe3f08b?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/911a2fe3f08b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 11:04:29 GMT</pubDate>
            <atom:updated>2023-02-06T11:04:29.456Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Adaptive LinearProgressIndicator Height in Compose]]></title>
            <link>https://medium.com/better-programming/adaptive-linearprogressindicator-height-in-compose-7943a956992?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/7943a956992</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Tue, 23 Aug 2022 14:59:12 GMT</pubDate>
            <atom:updated>2022-08-23T14:59:12.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>Render your Composable the size you want</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bw9s4PT54XRf8N_H" /><figcaption>Photo by <a href="https://unsplash.com/@itookthose?utm_source=medium&amp;utm_medium=referral">Sid Balachandran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When building components with Jetpack Compose, you can render them the way you want, thanks to the myriad of Modifier properties.</p><p>Most of the time, you can customize any components by overriding this parameter — you should always provide one, too, especially while building an SDK. Arguably, though, some Composables come with a stricter set of rules. That’s the case with the LinearProgressIndicator.</p><h3>The LinearProgressIndicator Use Case</h3><p>The native SDK exposes a Composable called LinearProgressIndicator that displays a horizontal progress bar. To match the <a href="https://material.io/develop/ios/components/progress-indicators/progress-views">Material guidelines</a>, the height matches LinearIndicatorHeight (which equals to 4.dp).</p><p>Here’s the Composable’s implementation (at the time I’m writing this, with Compose 1.2.1):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a3808fed539375d8682c4dbb28e470d/href">https://medium.com/media/5a3808fed539375d8682c4dbb28e470d/href</a></iframe><p>As you may notice, the Composable internally overrides its size with fixed values.</p><p>Of course, this doesn’t prevent you from changing it! Since the Composable naturally exposes a Modifier parameter, you can provide your own size. But what about if your size should fit another Composable’s size?</p><p>It’s time to look at the desired output. We would like to draw a progress bar that covers the whole content of a button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TAeyn68uwG38V_c1GhJZvQ.gif" /></figure><p>If we break this Composable down, we have:</p><ul><li>a Button</li><li>a LinearProgressIndicator</li><li>a Box that encapsulates both the Button and the LinearProgressIndicator</li></ul><p>I won’t cover the text and icon within the Button as they are irrelevant.</p><p>This brings us to this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d05ece295908f5e1680d066cb6299d4/href">https://medium.com/media/7d05ece295908f5e1680d066cb6299d4/href</a></iframe><p>If you give it a run, you will notice that the progress bar:</p><ul><li>still has a 4.dp height hence doesn’t fill the button.</li><li>doesn’t get clipped at the rounded corners. Try it with a red color, you’ll see it straight away.</li></ul><p>We can address the second issue easily. One way would be to delegate the shaping to the Box instead of the Button then clip its content.</p><pre>val shape = <em>RoundedCornerShape</em>(8.<em>dp</em>)<br><em>Box</em>(<br>    modifier = modifier<br>        .<em>background</em>(<br>            color = MaterialTheme.colors.primary,<br>            shape = shape,<br>        )<br>        .<em>clip</em>(shape),<br>)</pre><p>Let’s move on to the most interesting part. We can pass a hardcoded value to change the progress bar’s height. But we would like it to dynamically match the container height no matter what’s in it.</p><h3>Resizing The LinearProgressIndicator</h3><p>First, there are several ways to tackle this problem. You could dive into the art of making custom components by using a Layout and sizing the way you desire. For most cases, that would be preferable as it brings the most flexible pattern to draw your component.</p><p>Also, you could decide to ditch the LinearProgressIndicator over a Canvas and draw it yourself! Since this progress bar is meant to match the Material guidelines, it might be best not to tweak it further. And this would be one of the simplest shapes to draw in the Canvas. All you need to take care of is the animation part yourself.</p><p>Now, for the sake of the example, we will still use our LinearProgressIndicator and achieve the desired result with a few additional lines of code. We need to retrieve the Button height and pass it to the LinearProgressIndicator. We can leverage another useful Modifier called onSizeChanged(). This lambda passes its size when it gets redrawn as an argument. When received, convert it in Dp then remember it so that our LinearProgressIndicator recomposes with its new height.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e743113c8145d2b051555be11cd6589/href">https://medium.com/media/8e743113c8145d2b051555be11cd6589/href</a></iframe><p>For completeness, here is the final code of the Composable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61819e3e410442590ab758b348834d62/href">https://medium.com/media/61819e3e410442590ab758b348834d62/href</a></iframe><p>That’s all! This simple technique allows you to resize your components based on other component sizes. Note that you could reuse this pattern for any kind of component, although most of the time, the system should infer their size as you want using Modifier properties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7943a956992" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/adaptive-linearprogressindicator-height-in-compose-7943a956992">Adaptive LinearProgressIndicator Height in Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Google Map Compose Library For Android]]></title>
            <link>https://medium.com/better-programming/exploring-google-map-compose-library-for-android-af2a784f9508?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/af2a784f9508</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 16:14:30 GMT</pubDate>
            <atom:updated>2022-04-22T16:14:30.803Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to a new era for map-based Compose applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I72ujxO9CMMy3bJ4" /><figcaption>Photo by <a href="https://unsplash.com/@whmii?utm_source=medium&amp;utm_medium=referral">Will H McMahan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With the <a href="https://cloud.google.com/blog/products/maps-platform/compose-maps-sdk-android-now-available">recent release</a> of the <a href="https://github.com/googlemaps/android-maps-compose">Map Compose library</a>, it was perfect timing to try it out for the project I’m building with Jetpack Compose. In this application, I fetch a list of points of interest (POIs) from my server around a given area and mark them on the map.</p><p>I could have stuck with the <a href="https://developers.google.com/maps/documentation/android-sdk/start">View-based GoogleMap</a> and wrapped it within a AndroidView to invoke it in the Compose world. Especially if you’d need some advanced features as the Compose library still suffers from some limitations (more on this later).</p><p>But I expect some of you are as excited as I am to discover this new library made in Compose, for Compose.</p><p>This article will walk you through how to render a map with dynamic markers. We’ll also cover how to refresh these POIs while interacting with the map (panning, zooming, rotating).</p><h3>Configuring Your Map</h3><p>To render a map in your mobile application, you’ll need to go through this tedious part covered in this <a href="https://developers.google.com/maps/documentation/android-sdk/cloud-setup">documentation</a>. To summarize, you must:</p><ul><li>Create (or link) your Google Cloud Billing account to your project. In 2018, Google migrated to a pay-as-you-go plan that requires every project to configure upfront your payment details. In this tutorial, we’ll use a static map with the mobile SDK so we’ll stay under the radar. But depending on what you later plan for your app, there is a potential cost to consider. More information <a href="https://mapsplatform.google.com/pricing/">here</a>.</li><li>Enable the Map SDK for your project.</li><li>Create an API key. You can restrict it to avoid malicious usage by linking it to the SHA-1 certificate you’re using to sign your app.</li><li>Add the required dependencies and link your API key to your AndroidManifest file.</li></ul><p>The fun part begins once you’ve completed the above steps.</p><h3>Rendering The Map</h3><p>The library exposes a GoogleMap Composable as an entry point to render your map. Several optional arguments let you customize your map experience.</p><p>If you don’t provide any arguments, you’ll see a world map centered on the equator and the prime meridian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*aEHDbW5riGjJusdJeysMqw.png" /><figcaption>The world map from lat/lng 0</figcaption></figure><p>If you look at the constructor details, the GoogleMap takes a CameraPositionState with a default position at the latitude and longitude 0.</p><p>We’ll want to position our map around a specific location — or your current location but I won’t cover it in this article.</p><p>The map is driven by a single source of truth: the camera’s state CameraPositionState . Whenever you interact with the map, the state gets updated and a recomposition occurs.</p><p>As an example, I’ll center the camera around Bordeaux 🍷🥖🇫🇷. We’ll remember those coordinates using the rememberCameraPositionState function and pass them to the GoogleMap Composable. Here, I’ve arbitrarily set the zoom level to 12 to overlook the whole Bordeaux area.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfca10cb297da9bd08ab1fb8643b7b87/href">https://medium.com/media/bfca10cb297da9bd08ab1fb8643b7b87/href</a></iframe><p>When we run the app, this is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*Oq81jqFePyDc74Q6DG9JbQ.png" /><figcaption>Bordeaux area</figcaption></figure><p>That’s all you need to display a map with Map Compose! Impressive no? Now, it would be great to display some POIs.</p><h3>Displaying POIs Within a Perimeter</h3><p>The GoogleMap Composable accepts a content lambda as its last parameter to let you draw on the map. For that, we’ll want to look at the Marker Composable. It accepts a MarkerState — a wrapper for a LatLng object.</p><p>By default, the Marker will show a classic red pinpoint. You can customize it with its other parameters.</p><p>For my purposes, I’ve developed an API with a route that returns a list of objects around a certain location. It takes three parameters:</p><ul><li>a latitude</li><li>a longitude</li><li>a radius (in meters)</li></ul><p>From the CameraPositionState, we can retrieve the center position from the map’s camera:</p><pre>val centerLocation = cameraPositionState.position.target<br>val latitude = centerLocation.latitude<br>val longitude = centerLocation.longitude</pre><p>We’ll need some help computing the radius. The trick lies in converting the zoom level given by the map — a digit starting from 0 (the whole planet) to more than 21 — into a more human-friendly radius in meters. If you’d like to learn more about how Google renders the map, you’ll find <a href="https://medium.com/google-design/google-maps-cb0326d165f5">this article</a> very interesting.</p><p>Google provides a <a href="https://developers.google.com/maps/documentation/android-sdk/utility">maps utility library</a> that computes this distance for us by taking one corner of the map (top left for instance) with the center position.</p><pre>val topLeftLocation = cameraPositionState.projection?.<em>visibleRegion</em>?.farLeft<br>val radius = SphericalUtil.computeDistanceBetween(topLeftLocation, centerLocation)</pre><p>You’ll need to have your map ready to retrieve the above values (or the projection will be null). A good place to request them would be within the onMapLoaded lambda. That’s where I’ll ask my ViewModel to retrieve the locations of the POIs within the computed radius.</p><p>Finally, I iterate through my marker coordinates to generate all my Marker Composables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d75d3e1f512177ed3dd34a79a0fea2/href">https://medium.com/media/32d75d3e1f512177ed3dd34a79a0fea2/href</a></iframe><p>To simulate this, you can create a set of coordinates and give it to your GoogleMap Composable the same way you’d fetch them from an API.</p><p>Here is what you would see with the coordinates my server yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*mcOBB_Y4qC23WNyS2obCvQ.png" /><figcaption>A list of markers in the Bordeaux area</figcaption></figure><p>But this is only a snapshot of some POIs from what the camera sees. Ultimately, you’ll want to refresh those POIs while interacting with your map.</p><h3>Interacting With The Map</h3><p>The map lets you control what to display through gestures such as panning, zooming, or even rotating. Those interactions are bound to change what the camera sees. Hence, your POIs must change accordingly.</p><p>With Map Compose, you’ll once again rely on your single source of truth: the CameraPositionState. It has a property called isMoving that will turn to true as soon as the map moves. And it goes back to false when the camera becomes idle.</p><p>You may be tempted to simply wrap your fetching method within an if-condition like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a22efdbf5b8017c53faca2c7e8ecdd46/href">https://medium.com/media/a22efdbf5b8017c53faca2c7e8ecdd46/href</a></iframe><p>Although that would work, you’ll create excessive requests to your server!</p><p>That’s due to the nature of how the recomposition works. For instance, if you pan the map, the camera’s center location will change. As the map moves, you’ll refresh your POIs with the newly observed centered position. The fetched POIs are likely to differ, so your state will change, leading to a recomposition.</p><p>It means you’ll hit again the condition and refresh your POIs until your state stops changing — that could lead to a tremendous amount of requests!</p><p>Instead, you should treat this interaction as a <a href="https://developer.android.com/jetpack/compose/side-effects">side-effect</a> and wrap it accordingly. Since you’d like to trigger such an effect when the isMoving state changes, you can use LaunchEffect and pass this value as its key. Finally, refresh your POIs when the map stops moving.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3af7246e608590bd058be2bc460755d7/href">https://medium.com/media/3af7246e608590bd058be2bc460755d7/href</a></iframe><p>I’ve made a short video to illustrate how the refresh behaves. Even when I fling fast the map — the map blurs until the animation stops — the POIs get displayed when the map becomes idle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CC-KIFBwoK8k2shPyKAxDw.gif" /><figcaption>Refreshing POIs while panning and zooming the map</figcaption></figure><p>And what’s interesting with this Compose approach is the performance behind it! Because of the recomposition system, you can pass the list of POIs and the map will display only those markers. No need to take care of the lifecycle nor to make sure you’ve properly cleared your previous markers that the camera no longer displays. Not to mention the code is highly readable and just requires a few lines of code.</p><p>If you’re still here, congratulations! We’ve covered some basics on how to use the Map Compose and displayed POIs while interacting with the map.</p><p>Even though that might be enough for some of you, there are some things worth mentioning before a full dive into this library.</p><h3>Gotchas and limitations</h3><p>There are things that you may expect to have but are not yet ready with Map Compose. That’s the case with clustering.</p><p>This mechanism gathers a set of POIs within the same area. Without it, you may end up having a map crammed with markers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*07h0ixLrr8zSQwoq06zm1g.png" /><figcaption>Can you spot what you’re looking for amongst these 10 000 POIs?</figcaption></figure><p>Not only you can’t see much on the map, but you can imagine how poor the performance will be when trying to draw all these markers.</p><p>You can achieve clustering thanks to the ClusterManager from the util library mentioned above. Yet, this manager needs a GoogleMap from the View library — it can be confusing since the name matches, but it’s not the GoogleMap from the Compose library.</p><p>So as I’m writing these lines, the Map Compose library doesn’t support yet clustering. You can follow the open issue <a href="https://github.com/googlemaps/android-maps-compose/issues/44">here</a>.</p><p>In the meantime, you’re left with a couple of options:</p><ol><li>Keep using the former map API until clustering is supported.</li><li>Restrict your zoom level to a reasonable value. That could prevent rendering countless POIs as much as keeping the map from lagging. But this won’t replace a good clustering since your density of POIs may vary from one area to another. Your user experience may be degraded depending on the data you want to display.</li></ol><p>With that in mind, you’re all set to start using the Map Compose library. I’m positive it’ll become a game-changer for the map-based application as soon as it will catch up with the missing features.</p><p>In the meantime, keep track of their <a href="https://github.com/googlemaps/android-maps-compose">GitHub repository</a> for the upcoming releases. Have fun with the Map Compose!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af2a784f9508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/exploring-google-map-compose-library-for-android-af2a784f9508">Exploring Google Map Compose Library For Android</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose with Lifecycle-Aware Composables]]></title>
            <link>https://medium.com/better-programming/jetpack-compose-with-lifecycle-aware-composables-7bd5d6793e0?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd5d6793e0</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 15:16:14 GMT</pubDate>
            <atom:updated>2022-04-13T13:18:30.311Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bridging between Composable and View’s lifecycles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c29nadJv0btwT0gX" /><figcaption>Photo by <a href="https://unsplash.com/@zakariahada?utm_source=medium&amp;utm_medium=referral">Zakaria Ahada</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you come with an Android background, you should be familiar with the notion of lifecycles. Jetpack Compose introduces a new paradigm to build declarative UI using Composables. They come with a simplified lifecycle including three phases:</p><ul><li>The entering phase.</li><li>The recomposition phase.</li><li>The exiting phase.</li></ul><p>The <a href="https://developer.android.com/jetpack/compose/lifecycle">official documentation</a> describes in detail how a Composable behaves during its full lifecycle.</p><p>Now, you may be tempted to think the Composable’s lifecycle replaces the View’s lifecycle. Even though the naming aligns, we’re talking about two different notions.</p><p>For instance, even if you’d build a pure Compose application, your Composables may need to interact with the View’s lifecycle. That would be the case if you’d have a Composable refreshing some data when the application comes in the foreground.</p><p>Yet, the Composable knows nothing about the View’s lifecycle. You’ll need to bridge those two universes to bring this awareness to your Composables.</p><h3>The Resumed Composable Use Case</h3><p>Let’s assume we’re building a pure Compose application. Including a screen Composable ProductsScreen. This screen injects a ViewModel — via Hilt for instance — to fetch the products. We’d have the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90b35e56b994211114a7810a5dca43f6/href">https://medium.com/media/90b35e56b994211114a7810a5dca43f6/href</a></iframe><p>The ViewModel launches a coroutine when created and delegates the fetching operation to a repository.</p><p>Now, we’d like to refresh our products each time the user displays this screen. This can happen when the user goes to the background and re-enters the foreground — provided the system didn’t kill the application. Or if you’d navigate to a different screen then navigate back to the ProductsScreen.</p><p>You’ll soon realize our sample code doesn’t satisfy our requirements. The fetching will only be active during the first time the Composable appears. That’s because the ViewModel cancels the coroutine as the Composable exits the composition tree, but doesn’t relaunch it when re-entering the composition phase.</p><p>One solution would be to rely on the Composable’s entering phase to fetch your products. You could expose the fetch method from your ViewModel and call it from your Composable. Remember to call this method using a side effect. Otherwise, you’ll fetch your products not only when the composable gets visible but at each recomposition when its state will change!</p><p>If you’d like to call it once when the Composable enters its composition phase, you can use a LaunchEffect and Unit as a key — or true, as long as it doesn’t change during the composition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/986f688b30c085dd6654fb2d4f27242d/href">https://medium.com/media/986f688b30c085dd6654fb2d4f27242d/href</a></iframe><p>We haven’t checked all boxes though. Using the entering phase will help us refresh our products when navigating back to this screen. That’s not the case when the user has put the application in the background.</p><p>It matters to distinguish how Composable and View’s lifecycles work. But it’s also valuable to understand that you can combine them.</p><h3>Bringing the View’s Lifecycle To a Compose World</h3><p>In a pure Compose application, you must create an Activity as an entry point. We can rely on it to get the View’s lifecycle and pass it down to our Composable.</p><p>But passing down some events from the holding Activity to the Composable gets tedious. Especially when you have several parents Composables in between. Fortunately, we can directly make any Composables lifecycle-aware.</p><p>If you’re not familiar with lifecycle-aware components in Android, I’ve covered it with a similar use case in <a href="https://betterprogramming.pub/empowered-lifecycle-aware-viewmodel-for-android-f495de9a8170">this article</a>.</p><p>A similar configuration works with Jetpack Compose. But there exists a smarter, more “Compose-like” way to achieve it. Each Composable exposes the current lifecycle owner where you can retrieve the View’s lifecycle. Using a DisposableEffect side-effect, you can store the View’s lifecycle latest event and react upon it while safely detaching its observer when the Composable exits the composition tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d781650fd601701c83175b6c54be66d/href">https://medium.com/media/0d781650fd601701c83175b6c54be66d/href</a></iframe><p>All of it would quickly become boilerplate if more Composables would turn lifecycle-aware. We can write a Composable extension method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5774955b50d43f77f729011418f425ed/href">https://medium.com/media/5774955b50d43f77f729011418f425ed/href</a></iframe><p>With this configuration, you can react to the View’s lifecycle with a few additional lines of code.</p><h3>Lifecycle-Aware ViewModel for Jetpack Compose</h3><p>In the <a href="https://betterprogramming.pub/empowered-lifecycle-aware-viewmodel-for-android-f495de9a8170">previously linked article</a>, I’ve mentioned how vital ViewModel plays in your application scalability. Especially when some business logic is tightly bound to your View’s lifecycle.</p><p>Using Compose doesn’t absolve you from doing so — even though it makes the separation of concern easier.</p><p>With the above solution, the View still holds the responsibility of reacting to lifecycle events and requesting the fetch to the ViewModel. Ideally, the ViewModel should take care of it.</p><p>Using the same technique, we create another Composable extension method to let any LifecycleOwner observe the View’s lifecycle. Then, we let the ViewModel implement the DefaultLifecycleObserver interface. We can move all the logic into the ViewModel!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5850ff49f7c8ce0395dd8571ac34280/href">https://medium.com/media/f5850ff49f7c8ce0395dd8571ac34280/href</a></iframe><h3>Wrapping up</h3><p>We’ve seen that, with a simple use case, relying solely on the Composable’s lifecycle won’t make the cut. With the lifecycle-aware components library and a DisposableEffect, you can transfer the lifecycle events to the ViewModel.</p><p>Also, the testing process remains unchanged compared to my previous article. This means we can keep our lifecycle-aware ViewModel logic regardless if injected by a View or a Composable. Only the lifecycle binding differs — and it’s even more straightforward with Compose with the extension method!</p><p>I hope this will help you in your migration process towards Jetpack Compose while mitigating the impact on your code. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd5d6793e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/jetpack-compose-with-lifecycle-aware-composables-7bd5d6793e0">Jetpack Compose with Lifecycle-Aware Composables</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowered Lifecycle-Aware ViewModel For Android]]></title>
            <link>https://medium.com/better-programming/empowered-lifecycle-aware-viewmodel-for-android-f495de9a8170?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/f495de9a8170</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 15:47:15 GMT</pubDate>
            <atom:updated>2022-04-04T15:47:15.602Z</atom:updated>
            <content:encoded><![CDATA[<h4>Delegate your lifecycle events to your ViewModel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*87OBa0qB-VukSrUW" /><figcaption>Photo by <a href="https://unsplash.com/@lalunecreative?utm_source=medium&amp;utm_medium=referral">Matt Hudson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ViewModels exist to take away all business logic from the View. No matter how you architect your ViewModel, some logic remains tightly bound to the View’s lifecycle. For instance, a small use-case would be to perform some tracking each time you open a screen. Assuming this screen injects a ViewModel, and this ViewModel rightfully owns the tracking logic, then you’ll need to detect when to trigger such action.</p><p>Since the lifecycle belongs to the View’s realm, you could leave this to the View’s responsibility — overriding the onResume function for instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d7fe47a395b5498bdac958e629e4ea5/href">https://medium.com/media/0d7fe47a395b5498bdac958e629e4ea5/href</a></iframe><p>But let’s not forget why we’re using ViewModels. Eventually, we mean to extract this business logic into the ViewModel to test it. With this architecture, we could unit test the implementation — the track has been called with the right arguments, calling verify if you’re using <a href="https://site.mockito.org/">Mockito</a>.</p><p>Sadly, we fail to test our behavior. We cannot assert that the tracking took place when the user opened the screen. Only that the tracking is correctly implemented. That’s a huge difference! And not to mention it won’t scale well. If by accident, someone would delete this portion of code in your View, you’ll end up with:</p><ul><li>A regression since you won’t track anymore your open screen.</li><li>Some dead code in your ViewModel.</li><li>Green unit tests that cover an unplugged use case.</li></ul><p>Now that I’ve made my case, let’s see how we make our ViewModel lifecycle aware.</p><h3>Lifecycle Aware Components</h3><p>Becoming lifecycle-aware lets you observe any lifecycle events happening to a specific View. Basically, you transfer those events from the View to the ViewModel.</p><p>ViewModel already responds to lifecycle events via its onCleared callback. The ViewModel’s lifecycle differs from the View yet gets notified when it will no longer be needed.</p><p>To further empower its lifecycle awareness, we can rely on Google’s Jetpack library <a href="https://developer.android.com/topic/libraries/architecture/lifecycle">androidx.lifecycle</a>. When you want to make a component lifecycle-aware, simply implement its LifecycleObserver interface and declare it as an observer from the lifecycle owner you’d like to observe. If you don’t need to react to all lifecycle events, you can use the DefaultLifecycleObserver interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/373c764ee8f45671d7d5808ea271b0fb/href">https://medium.com/media/373c764ee8f45671d7d5808ea271b0fb/href</a></iframe><p>With this lifecycle-aware ViewModel, you no longer need to override onResume in your View. The ViewModel takes care of all business logic. Congratulations!</p><p>But what about tests? That’s why we’re doing this right?</p><h3>Testing, Testing</h3><p>I’ve written an empty shell to test our ViewModel</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/298308f764be17756b7342699fa99d8d/href">https://medium.com/media/298308f764be17756b7342699fa99d8d/href</a></iframe><p>To make this test work, we would like a mechanism transiting from one state to another. We’ll need three things:</p><ol><li>A LifecycleRegistry to manipulate the lifecycle state.</li><li>A LifecycleOwner we pass to the LifecycleRegistry.</li><li>A LifecycleObserver: the tested ViewModel for our use-case.</li></ol><p>To create a LifecycleRegistry, we can use the createUnsafe method specifically designed for tests. We’ll inject the LifecycleOwner to the LifecycleRegistry as a mock:</p><pre>val lifecycleOwner = mock&lt;LifecycleOwner&gt;()<br>val lifecycleRegistry = LifecycleRegistry.createUnsafe(lifecycleOwner)</pre><p>Then we’ll need to register the ViewModel to the LifecycleRegistry.</p><pre>lifecycleRegistry.addObserver(viewModel)</pre><p>Finally, you can point to the desired lifecycle state:</p><pre>lifecycleRegistry.<em>currentState </em>= Lifecycle.State.<em>RESUMED</em></pre><p>Here is our tested class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98338cf6865582af0b7ab5954aa4a1f/href">https://medium.com/media/a98338cf6865582af0b7ab5954aa4a1f/href</a></iframe><p>You can now test your ViewModel based on specific lifecycle states! We could go a bit further by eliminating some of this boilerplate.</p><p>One way would be to extract this into a class taking the lifecycle observer in its constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b3afcdf03f5d54e8a53fb7305f08022/href">https://medium.com/media/7b3afcdf03f5d54e8a53fb7305f08022/href</a></iframe><p>In your tested class, create an instance of it and change the lifecycle status with the provided public methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a647565757eb138a9022d7f13be056b/href">https://medium.com/media/7a647565757eb138a9022d7f13be056b/href</a></iframe><h3>Closing Thoughts</h3><p>Testing behavior over implementation can help you build scalable apps. While using the MVVM architecture, make sure to extract all business logic into your ViewModel.</p><p>By making your ViewModel lifecycle-aware, you delegate some logic belonging to the View to the ViewModel. Your View only gets to update its state and execute effects coming from the ViewModel. Nothing more!</p><p>While this article focuses on ViewModels, nothing prevents you from making other components lifecycle-aware. That could come in handy in some use-cases when the business holder component would need to access this information to perform some action without having to expose them to the View.</p><p>Always keep your view code to the minimum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f495de9a8170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/empowered-lifecycle-aware-viewmodel-for-android-f495de9a8170">Empowered Lifecycle-Aware ViewModel For Android</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining Animations With Jetpack Compose]]></title>
            <link>https://medium.com/better-programming/chaining-animations-with-jetpack-compose-b4ff6e2e047d?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ff6e2e047d</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 16:32:55 GMT</pubDate>
            <atom:updated>2022-10-27T13:37:13.138Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover how to run sequential and parallel animations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RAlldDgYzefOOJse" /><figcaption>Photo by <a href="https://unsplash.com/@messrro?utm_source=medium&amp;utm_medium=referral">Mehdi MeSSrro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to running animations individually, Google provides <a href="https://developer.android.com/jetpack/compose/animation">thorough documentation</a>. When it comes to chaining several animations — whether they are sequential or parallel — I’ve struggled to find the right resource.</p><p>Until I bumped into this video that summarizes exactly what I was looking for:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZ_T1bVjhMLk&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZ_T1bVjhMLk&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FZ_T1bVjhMLk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7bc3065f7ecfffc17cc8d22c69b75f2/href">https://medium.com/media/a7bc3065f7ecfffc17cc8d22c69b75f2/href</a></iframe><p>This video explains how to leverage coroutines to chain your animations. That was my missing piece to accomplish a shuffle animation. I would animate two cards that would translate back and forth while they would scale down until they both reach a middle point.</p><p>Look at the final effect by yourself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEgBV0GUz7T0tGuZ-PWLnw.gif" /></figure><p>Let’s have a look at the different animations being applied to achieve this shuffle effect.</p><h3>The Shuffle Effect</h3><p>If you look closely at the animation, we can split it into a set of animations. There are actually 3 sets themselves containing sometimes a set of animations:</p><ol><li>The opening: a slight scale down from 1 to 0.9%</li><li>The core: three parallel animations with the same duration where the scale down slowly continues until reaching 0.8%. Similarly, the opacity diminishes from 1 to 0.4%. Finally, we repeat five times the same back and forth translations at a faster pace.</li><li>The closing: we hide one card while the other gets its opacity reset to 1. The chosen card’s offset is set to 70% of the height between the two cards. Finally, after a small delay, the card animates back to the top of the screen while the scale goes back to normal.</li></ol><p>All those animations run both sequentially and simultaneously. They can be represented as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*FX2hnF9s5a6I6vnsQ75aPQ.png" /></figure><p>Now that we’ve illustrated how the animation should behave, let’s see how we can leverage coroutines to wrap them all.</p><h3>Chaining Animations With Coroutines</h3><p>Jetpack Compose uses coroutines to let you chain several animations. Whether they are sequential or simultaneous, you can create as many coroutines to create the desired effect.</p><p>We’ll start by building the skeleton of our shuffle animation. Since it includes both sequential and parallel animations, we’ll need to create several coroutines as well as some coroutineScope for the simultenaous aspect.</p><p>The skeleton should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67aead94ad500314b35aea733e4ba271/href">https://medium.com/media/67aead94ad500314b35aea733e4ba271/href</a></iframe><p>This skeleton bootstraps our animation by splitting them into subsets of coroutines.</p><p>As for the animations themselves, Jetpack Compose exposes an animate suspend method callable from a coroutine context.</p><pre>suspend fun animate(<br>    initialValue: Float,<br>    targetValue: Float,<br>    initialVelocity: Float = 0f,<br>    animationSpec: AnimationSpec&lt;Float&gt; = <em>spring</em>(),<br>    block: (value: Float, velocity: Float) -&gt; Unit<br>)</pre><p>As an example, let’s start with the enter animation. We would like to scale down our cards from 1 to 0.9.</p><p>We can start by saving a scale ratio and updating its value within the animate method.</p><pre>var scale by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(1f) <strong>}</strong></pre><pre><em>LaunchedEffect</em>(key1 = Unit) <strong>{<br>    </strong>animate(1f, 0.9f) <strong>{ </strong>value: Float, _: Float <strong>-&gt;<br>       </strong>scale = value<br>    <strong>}<br>}</strong></pre><p>Then we can apply this value to both our card composables.</p><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .<em>scale</em>(scale),<br>    // Other parameters<br>)</pre><p>The animate function will interpolate the scale value with a default spring effect. You can change this effect by overriding the animationSpec property.</p><h3>Back and Forth Translations</h3><p>This part of the animation deserves its own section. As a disclaimer, I want to emphasize I’m not advocating how I’ve handled this transition. The reason lies in its lack of scalability as much as a hunch there must be a better way out there. I encourage you to share your alternatives to further improve the overall quality of this animation.</p><p>Having said that, my approach works. I start by retrieving the position I want to translate to called finalOffset. In my case, since the cards swap, this value equals the card’s height and the padding between them.</p><p>I remember this value from the second card composable using the onGloballyPositioned<em> </em>method.</p><pre>val density = <em>LocalDensity</em>.current<br>val padding = 30.dp</pre><pre>var finalOffset by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(0f) <strong>}</strong></pre><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .padding(top = padding * 2)<br>        .<em>onGloballyPositioned </em><strong>{<br>            </strong>finalOffset = <em>with</em>(density) <strong>{<br>                </strong>it.size.height + padding.<em>toPx</em>() * 2<br>            <strong>}<br>        }<br></strong>        // Other properties<br>)</pre><p>We’ll need to store the interpolated offset while running the animation. Finally, the translation results in the final offset interpolated with the animated offset. We negate this value for the second card to translate in the opposite direction.</p><pre>var offset by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(0f) <strong>}</strong><br>val translation = finalOffset * offset</pre><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .<em>graphicsLayer</em>(<br>            translationY = translation<br>        ),<br>    // Other parameters<br>)</pre><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .<em>graphicsLayer</em>(<br>            translationY = -translation<br>        ),<br>    // Other parameters<br>)</pre><p>As for the offset computation, we’ll use the same mechanism as we did for scale. We need to apply two sequential animations where the offset goes from 0 to 1 then 1 to 0 to mimic a back and forth. To wrap this up, we repeat this cycle as many times as you want (five in this example).</p><pre><em>launch </em><strong>{<br>    </strong><em>repeat</em>(5) <strong>{<br></strong>        animate(0f, 1f) <strong>{ </strong>value: Float, _: Float <strong>-&gt;<br>            </strong>offset = value<br>        <strong>}<br>        </strong>animate(1f, 0f) <strong>{ </strong>value: Float, _: Float <strong>-&gt;<br>            </strong>offset = value<br>        <strong>}<br>    }<br>}</strong></pre><h3>Wrapping The Animations Up</h3><p>For the remaining animations, we will apply the same logic but on different properties. Let’s start by storing them all:</p><pre>var scale by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(1f) <strong>}<br></strong>var firstCardAlpha by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(1f) <strong>}<br></strong>var secondCardAlpha by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(1f) <strong>}<br></strong>var offset by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(0f) <strong>}</strong></pre><p>There is one important piece to mention though. Because we’re simultaneously manipulating different properties of our composable, we can’t rely anymore on the direct Modifier properties such as scale, alpha and offset. You’ll need to use the Modifier’s graphicsLayer property.</p><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .<em>graphicsLayer</em>(<br>            alpha = firstCardAlpha,<br>            scaleX = scale,<br>            scaleY = scale,<br>            translationY = translation<br>        ),<br>    // Other parameters<br>)</pre><pre><em>PlayerCard</em>(<br>    modifier = Modifier<br>        .<em>graphicsLayer</em>(<br>            alpha = secondCardAlpha,<br>            scaleX = scale,<br>            scaleY = scale,<br>            translationY = -translation<br>        ),<br>    // Other parameters<br>)</pre><p>The complete animation block should tend towards this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09019c61bb1a65d215e63b4bb54c7267/href">https://medium.com/media/09019c61bb1a65d215e63b4bb54c7267/href</a></iframe><p>You’ll probably end up with something slightly different as it should match your use case — not to mention there is some business logic behind I’ve hidden as it was not relevant for the article.</p><p>Chaining animations result in leveraging coroutines and changing composable intrinsic properties. Don’t hesitate to build amazing user experiences with intricate animations that make immediate sense to your users. With this shuffle animation, the user understands the randomness lurking behind.</p><p>I dearly hope this article will ease your approach towards chained animations with Jetpack Compose. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ff6e2e047d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/chaining-animations-with-jetpack-compose-b4ff6e2e047d">Chaining Animations With Jetpack Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Swing Effect With Jetpack Compose]]></title>
            <link>https://medium.com/better-programming/the-art-of-swing-effect-with-jetpack-compose-e6f4c8cb0d88?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f4c8cb0d88</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 17:33:11 GMT</pubDate>
            <atom:updated>2022-02-16T17:33:11.826Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to rotate things with an anchor point</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io5JLdpugBYHBsas" /><figcaption>Photo by <a href="https://unsplash.com/@remyloz?utm_source=medium&amp;utm_medium=referral">Remy_Loz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Compose has come a long way to challenge how to build declarative UI. And animating objects don’t fall short either. The API offers a unified toolkit to let you polish your effects.</p><p>Having said that, rediscovering a new API can be frustrating. You’ll bump into difficulties while trying to reproduce an effect you knew how to perform with the former animation API. That’s what happened to me while trying to swing an object like a pendulum. Here is what I wanted to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*7CIwhuiwrx0hGZfiLsL-Ng.gif" /><figcaption>The swing effect</figcaption></figure><p>At first sight, the animation looks like an infinite back and forth rotation from one angle to another. Nothing extraordinary, right? Let’s see how it goes!</p><h3>Building The Composable</h3><p>Before achieving the above effect, let’s build the composable we’ll want to swing. For the sake of example, I’ll not dwell on the arrow nor on the inner part of the rotated shape.</p><p>For this composable, we need two things: the shape we’ll rotate and the nail anchoring it. Given its simplicity, we can use a Surface for both components — drawing on a Canvas would be perfectly fine too. We can encapsulate both Panel and Nail composables within a Box with a TopCenter alignment to place the nail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d82ce19bd6481ed40c7d7dab80f9936/href">https://medium.com/media/2d82ce19bd6481ed40c7d7dab80f9936/href</a></iframe><p>The result should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*zG-sIkZ72-hQqwcFtqmM6Q.png" /></figure><p>To rotate our Panel composable, we must provide a dynamic angle. Since we want the shape to swing indefinitely, we can leverage the transition API with rememberInfiniteTransition . Then, we update the angle by changing its value from a starting point angleOffset to its final destination — I’ve used its negative counterpart for symmetry purposes but you could choose otherwise.</p><p>For the animation part itself, I’ve used a tween interpolation. Compose comes with many built-in animations to achieve the desired effect. I strongly suggest you take a look at their <a href="https://developer.android.com/jetpack/compose/animation">well-covered documentation</a>.</p><p>Finally, we apply this angle to the Panel’s Modifier using the rotate method. Here is the updated Panel ’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c6d30cc12df51fd66062a72634de11a/href">https://medium.com/media/4c6d30cc12df51fd66062a72634de11a/href</a></iframe><p>And its output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*g0tl9f9_lvRh6xP_4d9_Zw.gif" /><figcaption>Panel rotating on itself</figcaption></figure><p>Not really what we were expecting, right? The nail doesn’t look like he’s doing a proper job at pining the panel. There is a simple reason behind this: the rotation is anchored at the <strong>center</strong> of the panel. We need to shift its origin to its anchoring point: the nail.</p><h3>Shifting The Transformation Origin</h3><p>Before Compose, changing the anchoring point of a rotation transformation was no big deal. For instance, <a href="https://developer.android.com/reference/android/view/animation/RotateAnimation">RotateAnimation</a> lets you change the pivot directly in its constructor:</p><pre>public RotateAnimation (<br>    float fromDegrees, <br>    float toDegrees, <br>    float pivotX, <br>    float pivotY<br>)</pre><p>With Compose, the rotate method doesn’t let you change its pivot, nor any other seemingly related modifiers. Until you find it: transformOrigin.</p><p>It matters first to understand that all of the modifier transformation methods wrap layer operations on a composable. The rotate method is no stranger to that:</p><pre>@Stable<br>fun Modifier.rotate(degrees: Float) =<br>    if (degrees != 0f) <em>graphicsLayer</em>(rotationZ = degrees) else this</pre><p>It modifies the layer’s rotationZ property with the given angle. This hints to us that shifting the pivot would come from modifying a graphicLayer property.</p><p>The graphicLayer modifier has a transformOrigin property that defaults to TransformOrigin.Center. If you look closer at its implementation, it takes two attributes: pivotFractionX and pivotFractionY. By changing the origin, we can orient it to our nail location.</p><p>Given the nail position, that means center horizontally and nearly at the top of the y-axis. Then we apply our rotation directly on the rotationZ attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8438fe7277c85396bfee9bb423c4faf8/href">https://medium.com/media/8438fe7277c85396bfee9bb423c4faf8/href</a></iframe><p>It produces the following effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*zXv0_-enZeLRaoAIs93zBQ.gif" /></figure><p>Exactly what we wanted to do! What about if the element is already rotated as we could see in the introductory animation.</p><p>We’d first need to rotate our Swing composable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e10feb38c5232e6ea9dbbc74b0aa1fce/href">https://medium.com/media/e10feb38c5232e6ea9dbbc74b0aa1fce/href</a></iframe><p>Notice the Box’s alignment has changed to TopStart.</p><p>We’ve also adjusted our transformation origin because we’ve changed our referential by rotating the Box.</p><p>It gives the following animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*u3BHuUB2-eHSjJf6sd0GJQ.gif" /></figure><h3>The Art Of Transformation</h3><p>Changing the animation pivot doesn’t exclusively cover rotation. All transformations can benefit from this property. You should be aware it exists and its utility. It might come in handy for your future animations.</p><p>Rediscovering a new API can be frustrating at times. Be confident, though, that the Compose team has you covered. If you feel something is missing out in Compose, I’d recommend joining <a href="https://surveys.jetbrains.com/s3/kotlin-slack-sign-up">the Kotlin Slack Channel</a>. Members support each other and make the community grow. A dedicated room exists for Compose-related topics. It’s there I’ve come to ask for help — credits go to <a href="https://medium.com/u/c967b7e51f8b">Romain Guy</a> for guiding me towards the solution.</p><p>Finally, all of the above should be working with Compose Multiplatform– there is nothing Android-specific in this code.</p><p>More articles are on the way! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f4c8cb0d88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-art-of-swing-effect-with-jetpack-compose-e6f4c8cb0d88">The Art of Swing Effect With Jetpack Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Localized iOS Files For Android Codebase]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/converting-localized-ios-files-for-android-codebase-8f34ee8b34ba?source=rss-c11030d62971------2"><img src="https://cdn-images-1.medium.com/max/2600/0*HdzM8DV8n9CIBtoM" width="5184"></a></p><p class="medium-feed-snippet">Let your IDE do the heavy lifting</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/converting-localized-ios-files-for-android-codebase-8f34ee8b34ba?source=rss-c11030d62971------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/converting-localized-ios-files-for-android-codebase-8f34ee8b34ba?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f34ee8b34ba</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 15:25:04 GMT</pubDate>
            <atom:updated>2022-02-02T15:25:04.191Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Delight Your Users With a Segmented Progress Bar]]></title>
            <link>https://proandroiddev.com/delight-your-users-with-a-segmented-progress-bar-75cb18489585?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/75cb18489585</guid>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 12:28:09 GMT</pubDate>
            <atom:updated>2022-01-18T12:28:09.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>Open-sourcing this Jetpack Compose widget</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v7OyzwPs4jyIACSH" /><figcaption>Photo by <a href="https://unsplash.com/@jamesamolnar?utm_source=medium&amp;utm_medium=referral">James A. Molnar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve been following my stories, this is the sequel of an article I’ve recently published where I describe how you can draw a segmented progress bar. For those who haven’t, you can find it <a href="https://medium.com/betclic-tech/building-a-segmented-progress-bar-in-android-e3f198db393d">here</a>.</p><p>Following this article, I started to wonder how it would fare if I’d write it in Compose. Needless to say, Compose is one of the trendiest tools to build declarative UI as I’m writing. It allows you to easily build your UI components programmatically and order them on your screen. Meaning we no longer need an XML to declare our UI structure.</p><p>But when it comes to custom drawing, we’re already programmatically building our view using a Canvas. So what would be the point to do it with Compose? Does it bring any benefits?</p><p>Short answer: absolutely! Let me share with you my journey that eventually led to publishing this Compose widget into an <a href="https://github.com/StephenVinouze/SegmentedProgressBar">open-source library</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*ggmOpZ9ITX313wmRVjw4zg.gif" /><figcaption>Breath effect when reaching the last segment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*vcG_xmZ8GQFNr3gahpkmhg.gif" /><figcaption>“Kamehameha-like” animation</figcaption></figure><h3>Drawing Custom Shapes in a Canvas With Compose</h3><p>The logic behind drawing on a Canvas hasn’t changed with Compose. Compose exposes its Canvas widget to let you draw within a composable function. It relies on the same methods whether you want to draw a line, a rectangle, an arc, or a path.</p><p>Canvas accepts two parameters:</p><ul><li>a Modifier to define how the Canvas will be displayed on the screen</li><li>an onDraw lambda where all the drawing magic happens.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af54881fc58fe5e08111ea9aa34473de/href">https://medium.com/media/af54881fc58fe5e08111ea9aa34473de/href</a></iframe><p>To draw our segments, we’ll:</p><ol><li>reuse the SegmentCoordinatesComputer I’ve described in the previous article. This class computes a segment’s coordinates given a range of parameters (spacing, angle, etc).</li><li>store the computer’s state with the remember composable.</li><li>loop over the segmentCount argument and retrieve each segment’s coordinates.</li><li>draw the segment at the given coordinates. You can change the segment’s color and opacity — SegmentColor represents a data class with these two attributes.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0983094e69a873d111d5e779e30f7224/href">https://medium.com/media/0983094e69a873d111d5e779e30f7224/href</a></iframe><p>I’ve created an extension function to draw the segment as we’ll need it to draw the progress segment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c468f6440e886694e81ed28aec17d74/href">https://medium.com/media/2c468f6440e886694e81ed28aec17d74/href</a></iframe><p>Finally, drawing the progress bar results in retrieving its coordinates from the SegmentedCoordinatesComputer and calling the drawSegment extension method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39b897e4054e1e994c499992c99ba728/href">https://medium.com/media/39b897e4054e1e994c499992c99ba728/href</a></iframe><p>We’ve now rebuilt our segmented progress bar with Compose. But we’re still missing a key aspect of any progress bar.</p><h3>Animation with Compose</h3><p>So our widget doesn’t animate its progression. Pretty lame for a progress bar, right?</p><p>Not to worry though. Compose comes with several built-in APIs. I was baffled at how straightforward animations are with Compose!</p><p>In fact, you can bundle it in a single line of code! Since our progression consists of interpolating two integers, we can leverage the animateFloatAsState composable to recompose our widget with progress as a target value. Then, you need to pass the animatedProgress interpolated value to the computer and the recomposition will do the rest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ae95af128b2be6e6c8da2890750650c/href">https://medium.com/media/8ae95af128b2be6e6c8da2890750650c/href</a></iframe><p>By default, the progress will animate with a spring effect but animateFloatAsState composable comes with an animationSpec optional argument if you’d like to change its behavior.</p><h3>Was migrating to Compose worth it?</h3><p>I can safely say I’m glad I’ve invested in this endeavor. Not only it was a great first experience for me with Compose, but I now find the code easier to read compared to the former version. This is particularly useful when it comes to Open Source libraries.</p><p>Also, I’ve reduced the LOC by 180% 🤩</p><p>Finally, I’ve deeply appreciated the Preview tool while building the widget. It allowed me to directly see how the component was rendered on the screen. I’ve managed to break down my widget in many previews to ensure it answers all the different scenarios I could think of. When you have several parameters working together such as spacing and angles while changing the number of segments, the Preview helps a lot to visualize all these use-cases.</p><h3>Using This Widget in Your Project</h3><p>The last part of the journey was to make this widget available to the community. After all, the widget was already flexible enough to fit most of the use-cases.</p><p>The repository comes with a sample highlighting all you can do with this widget. I’ve also exposed a breath effect and a “Kamehameha-like” animations to give you an idea of how you could customize even further your component on top of it.</p><p>You can find the repository <a href="https://github.com/StephenVinouze/SegmentedProgressBar">here</a>. Feel free to post an issue you may find, I’ll do my best to address them promptly. Better though, if you’d have some requests or ideas to improve the widget, you’re welcome to open a pull-request 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75cb18489585" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/delight-your-users-with-a-segmented-progress-bar-75cb18489585">Delight Your Users With a Segmented Progress Bar</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blossoming as a Software Developer]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/blossoming-as-a-software-developer-f2f10035bcad?source=rss-c11030d62971------2"><img src="https://cdn-images-1.medium.com/max/2600/0*EL8CTaRDvJEY0ZHt" width="4136"></a></p><p class="medium-feed-snippet">Don&#x2019;t shy away from soft&#xA0;skills</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/blossoming-as-a-software-developer-f2f10035bcad?source=rss-c11030d62971------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/blossoming-as-a-software-developer-f2f10035bcad?source=rss-c11030d62971------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2f10035bcad</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stephen Vinouze]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 17:07:02 GMT</pubDate>
            <atom:updated>2021-12-21T17:34:35.781Z</atom:updated>
        </item>
    </channel>
</rss>