<?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 Baptiste Carlier on Medium]]></title>
        <description><![CDATA[Stories by Baptiste Carlier on Medium]]></description>
        <link>https://medium.com/@bapness?source=rss-716fc12c2b2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F7RsbAYbbxf50fXoOloRsQ.png</url>
            <title>Stories by Baptiste Carlier on Medium</title>
            <link>https://medium.com/@bapness?source=rss-716fc12c2b2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:12:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bapness/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[Taming the “God ViewModel”: Refactoring with Chain of Responsibility in Kotlin]]></title>
            <link>https://medium.com/@bapness/taming-the-god-viewmodel-refactoring-with-chain-of-responsibility-in-kotlin-6f3cafb92fea?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3cafb92fea</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 11:15:22 GMT</pubDate>
            <atom:updated>2025-12-22T11:15:22.492Z</atom:updated>
            <content:encoded><![CDATA[<p>As Android developers, we have all been there. You open a class named SearchViewModel to add a “small” feature, and you are immediately greeted by the Beast. What started as a simple API call has mutated into a 2,000-line hydra of validation logic, error handling, analytics tracking, and nested if/else blocks.</p><blockquote>At <a href="https://medium.com/u/441d81105564">Decathlon Technology</a>, on the <strong>Cube InStore</strong> project (our internal <a href="https://www.youtube.com/watch?v=LFgiytKFAMY">super-app</a> for store teammates), we faced exactly this situation. Our application is a toolbox used globally — from Paris to Sydney — allowing teammates to browse the catalog, manage stock, pick orders, and advise customers.</blockquote><p>Here is the story of how I transformed a legacy “spaghetti code” problem into a clean, scalable architecture using the <strong>Chain of Responsibility</strong> pattern, all while sticking to our modern stack: Kotlin, MVVM, Koin, and Clean Architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRlqRJKjnlVmPcril0oQBg.png" /></figure><h3>The Genesis of Chaos: Anatomy of a “God ViewModel”</h3><p>The story is classic. When we launched the product search feature, the requirement was simple: <em>“The user types an ID, we call the API, we show the product.”</em></p><p>But a living retail application evolves fast. Very fast.</p><ul><li><strong>Sprint 2:</strong> “Teammates need to search for query, not just type ID.”</li><li><strong>Sprint 5:</strong> “If the product ID is refurbished one, we should check and open the other product page.”</li><li><strong>Sprint 8:</strong> “Wait, for our users in London, we have a specific endpoint to call with product ID, not the default endpoint.”</li><li><strong>Sprint 12:</strong> “If the API fails, try a fallback search.”</li></ul><p>Over time, different feature teams and developers jumped in to add these use cases. Often pressed by deadlines, they added “just one more if condition.” The result? A SearchViewModel that knew too much. It was doing validation, orchestration, error formatting, and business logic.</p><p>This is what we call <strong>Technical Debt</strong>. Honestly, leaving this unchecked was an option, because… well… it works!<br>But surely it’s really messy, not maintainable, not scalable, and hard to test. If possible, we needed take time to do a nice refactor.</p><h3>Why “Chain of Responsibility”?</h3><p>We needed a solution that would allow us to:</p><ol><li><strong>Isolate Business Rules:</strong> Adhere to the <em>Single Responsibility Principle</em>.</li><li><strong>Simplify Testing:</strong> We wanted to unit test the “London logic” without mocking the entire world.</li><li><strong>Scale:</strong> Adding a new step (like checking a refurbished product ID).</li><li><strong>Enforce Order:</strong> Validation must happen before the network call if possible.</li></ol><p>The <strong>Chain of Responsibility</strong> pattern fits this perfectly. It allows you to pass a request along a chain of handlers. Each handler decides either to process the request or to pass it to the next link in the chain.</p><p>Also, the current behavior is that of a chain. Otherwise, like a decision tree, I wouldn’t have been able to implement this. And if things need to evolve in that direction in the future, we’ll have to remove the Chain of Responsibility, but we can probably continue to use its links (handlers).</p><h3>The Solution: From Theory to Kotlin</h3><p>Instead of the verbose Java implementations you might see in textbooks, I leveraged <strong>Kotlin Coroutines</strong> and <strong>Koin</strong> to make it elegant.</p><h3>1. The Contract (The Interface)</h3><p>I defined a generic interface. Every “step” of our search logic must implement this. Notice the suspend function — this is crucial for handling DB or Network calls without blocking the main thread.</p><pre>/**<br> * Base class for implementing the Chain of Responsibility pattern with coroutines.<br> */<br>public abstract class CoHandler&lt;Payload, Outcome&gt;(<br>    private val nextHandler: CoHandler&lt;Payload, Outcome&gt;? = null<br>) {<br>    /**<br>     * Processes the given input and returns an outcome or passes it to the next handler.<br>     */<br>    abstract suspend operator fun invoke(input: Payload): Outcome?<br>    /**<br>     * Passes the input to the next handler in the chain, if it exists.<br>     */<br>    protected suspend fun passToNext(input: Payload): Outcome? =<br>         nextHandler?.invoke(input)<br>}</pre><p>The Payload is a contract holding the inputs (query, errors), and Outcome is a result contract (different type of Success / Error / …).</p><blockquote>Note that I also made a non-suspendable version of the handlers and launcher.</blockquote><h3>2. The Links (Concrete Handlers)</h3><p>Instead of one giant function in the ViewModel, we broke the logic down into small, focused classes.</p><p>Example: The RedirectToProductListCoHandler. This handler checks the input to redirect to the product list page in order to launch other kind of search (by query, not ID).</p><pre>class RedirectToProductListCoHandler(next: CoHandler&lt;SearchPayload, SearchOutcome&gt;? = null) :<br>    CoHandler&lt;SearchPayload, SearchOutcome&gt;(next),<br>    KoinComponent {<br><br>    override suspend operator fun invoke(input: SearchPayload): SearchOutcome? {<br>        // If it doesn&#39;t match any kind of product id, we search for a list of products<br>        if (!input.searchTerm.matchesProductId()) {<br>            return SearchOutcome.GoToNavigateProductList<br>        }<br>        return passToNext(input)<br>    }<br><br>    private fun String.matchesProductId() = { /* Logic */ }<br>}</pre><p>We created other specific handlers:</p><ul><li>TraceabilityCoHandler for refurbished product</li><li>DefaultBehaviorCoHandler for default API</li><li>SpecificCountryCoHandler for calling another API</li><li>…</li></ul><h3>3. The Solution: From Theory to Kotlin DSL</h3><p>Instead of the verbose Java implementations you might see in textbooks, we leveraged Kotlin’s functional capabilities to make the implementation elegant and readable.</p><h4>A Nice DSL: ChainBuilder &amp; coChain</h4><p>Manually linking handlers (e.g., handlerA.next = handlerB) is error-prone and boilerplate-heavy. We wanted a declarative way to define our chains, something that reads like a sentence.</p><p>To achieve this, I created a small <strong>Domain-Specific Language</strong> (DSL) using a ChainBuilder and a helper function I called coChain (short for <em>Coroutine Chain</em>).</p><pre>public class ChainBuilder&lt;Payload, Outcome&gt; : KoinComponent {<br>    private val coFactories = mutableListOf&lt;(CoHandler&lt;Payload, Outcome&gt;?) -&gt; CoHandler&lt;Payload, Outcome&gt;&gt;()<br>    <br>    public fun addCoHandler(factory: (next: CoHandler&lt;Payload, Outcome&gt;?) -&gt; CoHandler&lt;Payload, Outcome&gt;) {<br>        coFactories += factory<br>    }<br><br>    public inline fun &lt;reified T : CoHandler&lt;Payload, Outcome&gt;&gt; injectCoHandler(qualifier: Qualifier? = null) {<br>        addCoHandler { next -&gt;<br>            get&lt;T&gt;(qualifier) { parametersOf(next) }<br>        }<br>    }<br>    public fun coBuild(): CoHandler&lt;Payload, Outcome&gt; {<br>        var previous: CoHandler&lt;Payload, Outcome&gt;? = null<br>        for (coFactory in coFactories.asReversed()) {<br>            previous = coFactory(previous)<br>        }<br>        return previous  ?: throw IllegalStateException(&quot;Chain must contain at least one handler&quot;)<br>    }<br>}</pre><pre>// The &quot;Magic&quot; DSL wrapper<br>public inline fun &lt;Payload, Outcome&gt; coChain(<br>    buildChain: ChainBuilder&lt;Payload, Outcome&gt;.() -&gt; Unit,<br>): CoHandler&lt;Payload, Outcome&gt; =<br>    ChainBuilder&lt;Payload, Outcome&gt;()<br>        .apply { buildChain() }<br>        .coBuild()</pre><p>This simple abstraction allows us to define complex logic chains visually, without worrying about the wiring plumbing.</p><h4>The SearchChainOfResponsibility (Domain Layer)</h4><p>In strict <strong>Clean Architecture</strong>, business rules and use cases belong in the Domain Layer. We didn’t want to construct this chain inside the ViewModel (Presentation Layer) or the Koin module (DI layer).</p><p>I created a dedicated class, SearchChainOfResponsibility, residing in the Domain. It acts as the single source of truth for the search business logic.</p><pre>internal class SearchChainOfResponsibility: KoinComponent {<br>    /**<br>     * Executes the chain of responsibility with the given [payload].<br>     */<br>    suspend operator fun invoke(payload: SearchPayload): SearchOutcome? {<br>        // Keep in mind that the order of handlers is important<br>        val cor = coChain {<br>            injectCoHandler&lt;RedirectToProductListCoHandler&gt;()<br>            injectCoHandler&lt;TraceabilityCoHandler&gt;()<br>            injectCoHandler&lt;SpecificCountryCoHandler&gt;()<br>            injectCoHandler&lt;DefaultBehaviorCoHandler&gt;()<br>        }<br>        return cor(payload)<br>    }<br>}</pre><p>By placing this in the Domain, we ensure that our core business logic is framework-agnostic. It doesn’t know about Android, ViewModels, or UI states. It just processes a request and returns a result.</p><h3>5. The Result: A Zen ViewModel</h3><p>This is what our SearchViewModel might look like after that. It has been stripped of all business logic. Its only job now is to hold the UI State (using StateFlow) and trigger the chain.</p><pre>class SearchViewModel(<br>    private val searchChain: SearchHandler, // Injected by Koin<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow&lt;UiState&gt;(UiState.Idle)<br>    val uiState = _uiState.asStateFlow()<br><br>    fun onSearchQuery(query: String) {<br>        viewModelScope.launch {<br>            _uiState.value = UiState.Loading<br><br>            // The ViewModel doesn&#39;t know HOW the search is done.<br>            // It just asks the chain to handle it.<br><br>            val result = searchChain.handle(SearchContext(query))<br><br>            _uiState.value = when (result) {<br><br>                is SearchResult.Success -&gt; UiState.Content(result.data)<br><br>                is SearchResult.Error -&gt; UiState.Error(result.message)<br><br>                // handle the Outcome your own way. It&#39;s just an example here.<br><br>                else -&gt; UiState.Idle<br><br>            }<br>        }<br>    }<br>}</pre><h3>The Benefits</h3><ol><li><strong>Testability:</strong> I can now write unit tests specifically for each Handlers, for SearchChainOfResponsibility, and for the ViewModelin a more convenient way.</li><li><strong>Scalability:</strong> If (for example) the Argentina country request specific logic for their region, we didn’t add another if (isArgentina) inside the ViewModel. We simply created an ArgentinaSpecificSearchCoHandler and injected it in the chain at the right stage. (Of course, finding something more semantic, not just related to the country’s name 😉)</li><li><strong>Readability:</strong> New developers joining the team don’t have to decipher a 2,000-line file. They can look at the SearchChainOfResponsibility class, see the chain order, and open the specific handler they need to work on.</li></ol><h3>Conclusion</h3><p>Refactoring isn’t just about cleaning up; it’s about preparing your codebase for the future. By applying the <strong>Chain of Responsibility</strong>, we turned a point of friction into a modular system that supports our growth.</p><p>Sure, this still adds a bit of boilerplate, and for us, it’s very much tied to our use of Koin. But I’ve also planned non-suspend or non-injection versions with Koin.</p><p>This solution isn’t perfect, far from it. We’re just starting to test it. But it provides a good foundation if you ever need to use this Chain of Responsibility pattern, if it fits your business logic.</p><blockquote>You can grab samples on my GitHub repository :<br><a href="https://github.com/BapNesS/kotlin-chain-of-responsibility">https://github.com/BapNesS/kotlin-chain-of-responsibility</a></blockquote><p>For a global project like ours, where reliability in stores is paramount, this kind of architectural investment is a real nice-have.</p><p>Don’t be afraid to move logic out of your ViewModels— your future self (and your team) will thank you. In fact, the ViewModel should contain as little business logic as possible. In our example, the ViewModel had become a God ViewModel, but this can sometimes happen at the Domain layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3cafb92fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modernizing website updates with Kotlin Script and GitHub]]></title>
            <link>https://medium.com/@bapness/modernizing-website-updates-with-kotlin-script-and-github-1e262c70dd5b?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e262c70dd5b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[kotlin-script]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 22:22:36 GMT</pubDate>
            <atom:updated>2024-12-31T07:01:51.356Z</atom:updated>
            <content:encoded><![CDATA[<p>During this winter holiday, I’ve decided to modernize the update process of my <a href="http://baptistecarlier.com/">personal website</a> with Kotlin Script. While the site is somewhat outdated, it remains a legacy personal project, and I enjoy using it to experiment.</p><h4><strong>The problem</strong></h4><p>The website is mainly a static page. Since few years it’s saved on a private GitHub repository. In order to update the content of the online version, it requires:</p><ul><li>Update the HTML on GitHub or on local</li><li>Retrieve the data</li><li>Use an FTP client (or the hosting service WebFTP client) to upload it</li></ul><p><strong>It’s far from efficient</strong>, and maybe that’s why I didn’t update the content for so long. So now the goal is to make the update process smoother, more automated, and enjoyable to work on.</p><p>Inspired by resources such as <a href="https://mbonnin.net/2024-11-21_state-of-kotlin-scripting/">Martin Bonnin’s article</a> and <a href="https://www.youtube.com/watch?v=bhOXxX8EhZI">Benjamin Code’s YouTube video</a>, I decided to leverage <strong>Kotlin Script</strong> (*.main.kts) to simplify the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*frmnTnnmLJWofYD7-gm07Q.png" /></figure><h3>Clean the existing</h3><p>The first step is to reorganize the site’s files and folders in the existing GitHub repository.</p><p>The idea is to centralize <strong>assets</strong> (images, CSS, etc.) and generate the final site in a build folder. This structure simplifies automation and avoids dependencies on the state of deployed files.</p><blockquote>I know… of course, I could use one of the many popular JavaScript or TypeScript frameworks to handle this task. But let’s face it: I’m a mobile developer at heart, and using Kotlin felt both natural and fun. Why not try to discover Kotlin script instead of use those “industry standards”?!</blockquote><h3>JSON as a source of truth</h3><p>Because the current website content is relatively simple, I decide to convert it into a <strong>JSON</strong> file. This provided a clean and easily manageable source of truth while also giving me the opportunity to experiment with <strong>Kotlinx Serialization</strong> in my Kotlin script. Initially, I uses <strong>Jackson for Kotlin</strong> (com.fasterxml.jackson.module:jackson-module-kotlin) because of its simplicity. But, as the project progressed, I decided to switch to Kotlinx Serialization, which is the standard I typically use for most projects.</p><p>Kotlinx Serialization integrates seamlessly with the Kotlin ecosystem, offering compile-time safety and idiomatic syntax. By enabling the compiler plugin and fine-tuning the project configuration, I found it to be perfectly capable of addressing the JSON needs of my project. Its multiplatform support make it a better long-term choice for maintaining the project consistently across environments (if I need).</p><p>Here are both ways to serialize :</p><pre>/**<br> * JACKSON<br> */<br><br>@file:DependsOn(&quot;com.fasterxml.jackson.module:jackson-module-kotlin:2.15.2&quot;)<br><br>import com.fasterxml.jackson.databind.DeserializationFeature<br>import com.fasterxml.jackson.databind.ObjectMapper<br>import com.fasterxml.jackson.module.kotlin.readValue<br>import com.fasterxml.jackson.module.kotlin.registerKotlinModule</pre><pre>/**<br> * KOTLINX SERIALIZATION<br> *<br> * Run with:<br> *  kotlin -Xplugin=/opt/homebrew/opt/kotlin/libexec/lib/kotlinx-serialization-compiler-plugin.jar skulptor.main.kts<br> * or<br> *  kotlin -Xplugin==$(dirname $(realpath $(which kotlin)))/../libexec/lib/kotlinx-serialization-compiler-plugin.jar skulptor.main.kts<br> */<br><br>@file:DependsOn(&quot;org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3&quot;)<br><br>import kotlinx.serialization.json.Json<br>import kotlinx.serialization.Serializable</pre><pre>private inline fun &lt;reified T&gt; getJsonContent(<br>    filePath: String,<br>    serializationType: SerializationType<br>): T = safeFileRead(filePath) {<br>    val dataAsJsonString = File(filePath).readText()<br><br>    return when (serializationType) {<br>        SerializationType.KOTLINX -&gt; {<br>            val json = Json {<br>                ignoreUnknownKeys = true<br>            }<br>            json.decodeFromString(dataAsJsonString)<br>        }<br><br>        SerializationType.JACKSON -&gt; ObjectMapper()<br>            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)<br>            .registerKotlinModule()<br>            .readValue(dataAsJsonString)<br>    }<br>}</pre><blockquote>Now that I have a beginning of something, I can give my script project a name, <strong>SKulptor</strong>.</blockquote><h3>Generating HTML with Kotlin</h3><p>Now that I can play with the data, let’s try to generate a HTML DOM from SKulptor.</p><p>At first, I considered creating a custom DSL for HTML in Kotlin. I even started drafting some helper functions to define HTML elements programmatically. While this could be a great experiment, I quickly realize that reinventing the wheel isn’t the smartest use of time — especially when excellent libraries like <a href="https://github.com/Kotlin/kotlinx.html">JetBrains’ <strong>kotlinx-html</strong> already exist</a>. Leveraging the official <strong>kotlinx-html</strong> library (org.jetbrains.kotlinx:kotlinx-html-jvm) allows me to focus on rebuilding my site incrementally while taking advantage of Kotlin’s safety and flexibility.</p><pre>div(&quot;row&quot;) {<br>    div(&quot;col-md-8 col-md-offset-2 text-center fh5co-heading&quot;) {<br>        h2 { +globalContent.about.title }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*1UdRfpvn7_PknpYHecOgnA.png" /></figure><p>To streamline testing, I set up a lightweight Kotlin project using a <strong>Ktor</strong> server to serve static HTML. This setup enable rapid validation of changes before integrating them into the GitHub workflow.</p><pre>fun Application.module() {<br>    routing {<br>        staticResources(remotePath = &quot;/static/&quot;, basePackage = &quot;static&quot;)<br>    }<br>}</pre><p>From there, I have to rewrite all the HTML using the DSL, but with some help from <strong>Copilot</strong>, the process was much faster. That said, it’s not always perfect! <strong>It’s crucial to thoroughly review the generated code to ensure everything works as expected</strong>.</p><blockquote>This year, I’ve had many opportunities to use <strong>Copilot</strong> and <strong>ChatGPT</strong> extensively in my day-to-day work as a Software Engineer/Tech Lead.</blockquote><blockquote>They’ve been excellent productivity boosters for tasks like writing unit tests, generating documentation, and handling repetitive conversions. In 60%/70% of cases, they deliver solid results, making them invaluable for routine tasks.</blockquote><p>HTML is done, now…</p><h3>Let’s automate the deployment with GitHub Actions</h3><p>I need to do 2 things :</p><ol><li>Generate the HTML from Kotlin script</li><li>Upload the built result on my FTP</li></ol><p>To achieve this, I’m using the GitHub Action the following workflow that will be triggered on every pull requests:</p><pre># pull_request.yml<br><br>name: &quot;Skupltor on PR&quot;<br>on:<br>  pull_request:<br>    types: [opened, synchronize, reopened]<br><br>jobs:<br>  run-kotlin-script:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: &quot;Checkout repository&quot;<br>        uses: actions/checkout@v3<br><br>      - name: &quot;Grant execute permission for gradlew&quot;<br>        run: chmod +x skulptor.main.kts<br><br>      - name: &quot;Run Skupltor&quot;<br>        uses: sureshg/kts-exec@v2.7<br>        with:<br>          script: &quot;skulptor.main.kts&quot;</pre><p>This action allowed me to execute the Kotlin script seamlessly without needing additional configurations like granting execute permissions manually. It streamlined the process significantly.</p><p>Now the only missing part is the SFTP (not FTP or FTPS, as I initially thought) upload to the hosting provider :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8c4pF9W7AhACacm1--bX1Q.png" /></figure><p>So, I add a second workflow to handle when PR is merged into the main branch. By the way, it will also create a nice tag + release.</p><pre># on_main.yml<br>name: &quot;Deploy from main&quot;<br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  run-kotlin-script:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      # same as pull_request.yml<br><br>      - name: &quot;Get tag&quot;<br>        run: echo &quot;tag=$(date &#39;+%Y%m%d_%H%M%S&#39;)&quot; &gt;&gt; $GITHUB_ENV<br><br>      - name: &quot;GitHub Release&quot;<br>        uses: actions/create-release@v1<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}<br>        with:<br>          tag_name: &quot;${{ env.tag }}&quot;<br>          release_name: &quot;${{ env.tag }}&quot;<br><br>      - name: &quot;Deploy via SFTP on WEBSITE&quot;<br>        uses: Dylan700/sftp-upload-action@latest<br>        with:<br>          server: ${{ secrets.FTP_HOST }}<br>          username: ${{ secrets.FTP_USERNAME }}<br>          password: ${{ secrets.FTP_PASSWORD }}<br>          port: 22<br>          delete: true<br>          uploads: |<br>            ./build/ =&gt; ./prod/</pre><h3>Final outcome</h3><p>Now, <strong>updating my site is easy</strong>. All I need to do is to modify the JSON file and to create a PR. Once validated and merged into main, the site is automatically generated and deployed. It takes about 2m 35s.</p><ul><li>No FTP client required anymore</li><li>No need to fetch the website on a device. I can do it from GitHub from web or from the application</li></ul><p>I’m thinking about going further and try <a href="https://kotlinlang.org/docs/wasm-overview.html">Kotlin WASM</a> at some point but still knowing Kotlin script is nice.</p><h3>TL;DR</h3><p>This project was an excellent opportunity <strong>to explore Kotlin Script</strong>. If you find yourself in a situation you could create a shell but you are tired of BASH command lines, encourage you to explore Kotlin script. They make the process both powerful and enjoyable.</p><p>Resources:</p><ul><li><a href="https://kotlinlang.org/docs/custom-script-deps-tutorial.html">Get started with Kotlin custom scripting — tutorial</a></li><li><a href="https://kotlinlang.org/docs/typesafe-html-dsl.html">Typesafe HTML DSL</a></li><li><a href="https://kotlinlang.org/docs/type-safe-builders.html">Type-safe builders</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e262c70dd5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Gradle dependencies to TOML format, with ChatGPT]]></title>
            <link>https://medium.com/@bapness/convert-gradle-dependencies-to-toml-format-with-chatgpt-18b68c442f7d?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b68c442f7d</guid>
            <category><![CDATA[toml]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[version-catalog]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Wed, 31 May 2023 07:21:23 GMT</pubDate>
            <atom:updated>2023-05-31T07:30:45.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Bing Image Creator + DALL-E" src="https://cdn-images-1.medium.com/max/1024/1*HQnFu7TqyHDzFjuk8fMe2Q.png" /></figure><blockquote><em>I recently told my 9 years old daughter that Internet was a tremoudous change in the way of communicating and working when I grown up.<br></em>Yes, saying this tells me that I’m kind of old.</blockquote><blockquote><em>I also told him that her generation would certainly be changed by the arrival of AI.</em></blockquote><p>AI is not “that new” anymore. Just few months and it keeps going really fast. <strong>Now, I begin to use it for personal or technical tasks. In the post, you’ll find a small example about how you can do it too.</strong></p><p>Notice that it’s just one way. You can imagine others by training yourself to find the right prompts.</p><p>I’m <a href="https://developer.android.com/https://developer.android.com/build/migrate-to-catalogsbuild/migrate-to-catalogs">migrating builds of few personal Android project to version catalogs</a>.</p><p>TOML version catalogs are a feature introduced in Gradle 7.0, which allows you to define and manage dependency versions in a separate catalog file written in TOML format. TOML file provide a centralized way to manage and share dependency versions across multiple modules. It’s a new standard for Modern Android Development, and I think it’s time to switch to TOML.</p><p>At the beginning, to accelerate the convertion, I used Google Sheet. Excel and Sheets can be really useful when you masterize few functions. <em>(</em>I learn from the best, Eric 😉)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fs0kfBuqF62ve0zIykYOUQ.png" /></figure><p>Then I’ve started to think about all this trend about AI. Blog post, articles, videos, talks, and also the Google I/O 2023 main keynote… it’s time to dive in.</p><blockquote><a href="https://chat.openai.com/">https://chat.openai.com/</a></blockquote><h3>My prompts</h3><h4>1. Give a small context</h4><p>First step is to give ChatGPT the context for our conversation. What is its purpose.</p><p>So let’s say that like me :</p><pre>You&#39;re an Android and Kotlin developer.</pre><h4>2. Ensure it knows TOML</h4><p>To be sure the format will be the one I want, I just copy paste example from the official Android documentation for version catalog.</p><pre>You know TOML. Here&#39;s a nice example about how to convert Android dependencies to TOML:<br><br>From:<br><br>dependencies {<br>   implementation &#39;androidx.core:core-ktx:1.9.0&#39;<br>}<br><br>To:<br><br>[versions]<br>ktx = &quot;1.9.0&quot;<br><br>[libraries]<br>androidx-ktx = { group = &quot;androidx.core&quot;, name = &quot;core-ktx&quot;, version.ref = &quot;ktx&quot; }<br><br>Let’s say that in the Android build.gradle.kts file, to use the dependency, we should define it like this :<br><br>dependencies {<br>  implementation libs.androidx.ktx<br>}</pre><p>Yes we can assume that he knows it but a reminder can be useful.</p><p>And don’t bother about your input format. Raw format works great!</p><h4>3. Make the magic happen</h4><p>In my build.gralde files, I often use root project variables or buildSrc references. I will clean after the migration, but to differenciate TOML’s version attribut from version.refattribut, I specify ChatGPT to replace unknown versions.</p><p><strong>And now, I enter my data :</strong><br>(replace with yours)</p><pre>Use &quot;xxx&quot; as version if you don&#39;t know it exactly.<br>Don’t forget the TOML version tag.<br><br>Here&#39;s the Android dependencies to convert in TOML:<br>    implementation &#39;androidx.appcompat:appcompat:1.6.1&#39;<br>    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;<br>    implementation &quot;androidx.datastore:datastore-preferences:1.0.0&quot;<br>    implementation &#39;androidx.lifecycle:lifecycle-runtime-ktx:2.6.1&#39;<br>    implementation &#39;com.jakewharton.timber:timber:4.7.1&#39;</pre><p>It’s a bit amazing to see how easy it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h71ldYm_kkMJea-de5iBvw.png" /></figure><p>Everything is set up.<br>I can copy/paste my TOML code.<br>I can copy/paste my build.gradle code.<br>I just have to fill the kotlin_stdlib version. 🤓</p><h4>4. Going further</h4><pre>Comment the generated TOML code by explaining the purpose of every library.</pre><p>For big projects there might be a lot of dependencies.<br>You can enhance the generated code with few lines of comment. Almost everybody on your team will be happy to have few comments.</p><p>It’s not working 100% fine on this part. But still, it’s amazing.</p><p>So far, it’s not perfect and you’ll have to check the generate code/comment. Don’t commit stupidly please. 🙂</p><p><a href="https://chat.openai.com/share/efe33dd8-123c-4363-9f91-5d4edade1ccb"><strong>📌 Here’s the full ChatGPT conversation</strong></a></p><p>Last thing, honestly it took me the same time to write the Google Sheet file than find the right ChatGPT prompts. It’s just an example about how developers can use AI.<br>I’m sure more AI tools will appear inside our already existing ones, like:</p><ul><li><a href="https://developer.android.com/studio/preview/studio-bot">Studio Bot</a> in Android Studio</li><li><a href="https://www.adobe.com/products/photoshop/generative-fill.html">Generative Fill</a> in Adobe Photoshop</li><li>…</li></ul><blockquote>Twitter : <a href="https://twitter.com/bapness">@bapness</a><br>YouTube : <a href="https://www.youtube.com/@baptistemobiledev">@baptistemobiledev</a><br><a href="https://www.linkedin.com/in/baptiste-carlier/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b68c442f7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live coding on stage, the right way]]></title>
            <link>https://medium.com/@bapness/live-coding-on-stage-the-right-way-c176ae4b8a0d?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c176ae4b8a0d</guid>
            <category><![CDATA[talks]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[livecoding]]></category>
            <category><![CDATA[ide]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 13:28:46 GMT</pubDate>
            <atom:updated>2023-05-01T06:58:28.526Z</atom:updated>
            <content:encoded><![CDATA[<p>Few days ago, <a href="https://medium.com/u/b9ea1e80ac85">Antoine Robiez</a> and I were on stage at <a href="https://androidmakers.fr/">Android Makers</a>, speaking and demonstrating in front of a bunch of people. By <em>demonstrating</em>, I mean that a part of our talk was live coding.</p><p>It was the second time we made this talk. But this time, we anticipated few things just to be sure everything went OK. <strong>Here’s few keys to do secure your live coding demonstration on stage.</strong></p><p>It’s a Android developer point of view with Android Studio as IDE, but if it’s not your case, I think most of those advices will match your fits.</p><h3>1. Prepare your code base</h3><h4>Compilation time</h4><p>First thing, you’ll build and run your project maybe several times on stage. To gain time, you have to <strong>ensure a fast compilation time</strong>. Reducing this time is reducing the blanks you’ll have to fill. 😄</p><p>So be sure to <strong>remove everything unnecessary</strong>: dependency injection, unnecessary ressource, … everything not mandatory should be removed.</p><h4><strong>Fallback #1: branches</strong></h4><blockquote>Everything will be OK. Yeah, sure!</blockquote><p>But if not, branches will be a great fallback solution.</p><p>You should be able to switch easily from one branch to another. Ideally do it inside you IDE and the fastest way ever. Try to get shortcuts or with minimum actions required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g59eHXYSaxMMHBXWClyPuQ.png" /></figure><pre>[Terminal tab] git checkout -f am23/step-2</pre><h4>Dependencies</h4><p>Your talk is coming soon. So don’t update your external dependencies or your IDE anymore!</p><p>In our case, many things should be updated:</p><ul><li>Jetpack libraries</li><li>Kotlin 1.8</li><li>Android Gradle Plugin</li><li>Android Studio Electric Eel ➡️Android Studio Flamingo</li></ul><p>We upgraded many of them but from a point of time, we’ve decided too don’t upgrade to project anymore.</p><p>It’s working. It’s building. It’s OK. ✅</p><h4><strong>TODOs !</strong></h4><p>During your demo, you’ll have to reach specific lines to add or replace code. TODOs are useful mainly due to the IDE tab.</p><p>You’ll see all of them, and with a good naming convention (number? emoji? colored emoji ?), you’ll reduce the time spent finding the right lines.</p><blockquote>It could have been bookmarks.<br>But bookmarks are stored into the IDE, not to your repository. It matters if you’re not speaking alone.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8xQovGIIFwAdYp8tOacsg.png" /><figcaption>Branches + TODO = best combo 💙</figcaption></figure><h3>2. Prepare your IDE</h3><p>Let’s see what we can do from Android Studio itself.</p><h4>Clean up your IDE</h4><p>First, clean up your UI. IDE interface are very customizable. It’s nice for productivity. But it can distract you and the audience during your talk.<br>What should they look at?</p><p><strong>An easy solution is to remove everything unnecessary : clean your opened file tabs and your IDE tabs.</strong></p><p><em>Build variants</em>, <em>Structure</em>, <em>Gradle</em>, … it’s up to you to see which views are relevant and which one you should keep. My advice is to remove everything you can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*dPTqQhVsoZdJ4pLIjNRgDA.png" /></figure><h4>Live Templates 🖤</h4><p>Have yourself a break. Use <a href="https://twitter.com/bapness/status/1364256904231460864">live templates</a>. 😎</p><p>This <a href="https://medium.com/u/50879ece1436">JetBrains</a>’s IDE feature is a very powerful tool on a daily basis.<br>(I think I’ll write a publication just on this later)</p><p>And it’s also really useful on stage for two reasons :</p><ol><li>Your code will be cleaner.<br>Previously we manage our live coding with uncomment section. It’s easy but on a small european keyboard, it’s not convenient. That also means that, if you edit several times the same code, it may not be clearly readable for the viewers.<br>By using live template, you’ll just have to call the shortcut to complete the missing part. Not erase and uncomment code. 🤔</li><li>Your talk will be more professional:<br>- You have a TODO.<br>- Then you replace the missing part with just a simple word.<br>- Tape Enter. Completion is done!<br>- Then you can just focus on the explanation. 👍</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYyIwZy2NqgtUDaf06faZg.png" /></figure><p>Obviously you’ll have to have a <a href="https://twitter.com/bapness/status/1652291986479628290">find the right way</a> to manage your template abbreviation. But it’s up to you to find your own.</p><h4><strong>➡️ Pro tip for live templates: </strong>Save and share them!</h4><blockquote><strong>Story time:</strong></blockquote><blockquote>We did not have much time to prepare our presentation. Wze were not available to meet regularly. So we were each mainly working on our own for a while.</blockquote><blockquote>We had to find a way to share our Live Templates because we were working on our own computers.</blockquote><p>You can share your Android Studio Live Template with a simple trick: a share repository.</p><ul><li>You can find your Live Template location.<br>It might be something like /Users/John/Library/Application Support/Google/AndroidStudio2022.2/templates .</li><li>Create a git repo and share it!</li><li>Then create a symbolic link like:</li></ul><pre>cd &quot;/Users/John/Library/Application Support/Google/AndroidStudio2022.2/templates&quot;<br>ln -s &quot;/Users/John/Documents/github/compose-animations-livetemplates/Android_ComposeAnimationTalk.xml&quot; Android_ComposeAnimationTalk.xml</pre><ul><li>Push/pull really often <em>et voilà</em> 😉</li></ul><h4>Comment regions</h4><p>Did you know that you can <a href="https://blog.jetbrains.com/idea/2012/03/custom-code-folding-regions-in-intellij-idea-111/">make regions</a>?</p><p>We didn’t use them on stage but I saw few speaker did it. It helps the audience to focus on a specific part of your code. Then you unfold the regions as you go.</p><h4>Mirroring your device</h4><p>Since Android Studio Dolphin (experimental), you can mirror your device directly inside the IDE. It’s sable since Flamingo. It’s really efficient and easy to use it inside the IDE.</p><p>But be sure to try it before your demo.</p><blockquote>No need <a href="https://github.com/Genymobile/scrcpy">scrcpy</a> and <a href="https://www.vysor.io/">Vysor</a> anymore. Farewell bros! 👋</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvSjTX6qgXotKKpA9rdVeg.png" /></figure><h4>Prepare your device</h4><p>Other tip with your device (pick those you need):</p><ul><li>Turn off notifications</li><li>Turn on <em>Do Not Distrube</em> mode</li><li>Turn on plane mode</li><li>Disable auto-rotation</li><li>Show taps to show where you point your finger (<em>Developer options &gt; Input</em>)</li><li><a href="https://developer.android.com/studio/debug/dev-options#general">Enable demo mode</a> to clean the status bar</li><li>Ensure battery is full</li></ul><h3>3. Prepare your slides</h3><h4>Fallback #2: put screenshots/videos into your slides</h4><blockquote>Everything will be OK. Yeah, sure!</blockquote><p>But if not, <strong>videos of the results will be a great fallback solution</strong>.</p><p>You have branches. So you can move to the next step of your demo.<br>Don’t waste your time trying to find why it’s not working.</p><p>You’re in front of people. You and they don’t need you to debug your code. Except if it’s a way to explain a common problem that happens often.</p><p>So, just in case you’ll be in trouble, <strong>you can add screenshots/videos into your slides. This way you’ll show how it should work.</strong> And they see the result instead wasting their time in front of you. Looking for the reason why it’s not working.</p><p>And if all goes well, skip the result slide. You’ll just waste 1 seconde.</p><h4>Train, repeat, train, repeat, … and enjoy 😁</h4><p>It looks like a dumb advice but obviously it’s the most important one.</p><blockquote>Train yourself.<br>Pull your repository (codebase and templates)<br>Try things.<br>Repeat your tasks.<br>Prepare and practice your live template.<br>Train how fast you can switch from a branch to another.<br>Think about when you should do it.<br>Test your compilation/build/run time.<br>See what you can do during the compilation time; or where your can take time to explain.</blockquote><p>Surely you’ll have to spend <em>a looot of time</em> training yourself speaking in front of people. But if you want to do live coding, it’s that you are able to explain what you do.</p><p><strong>Spoiler:<br></strong>You’ll not get a <em>Wahoo Effect</em> every time with just few lines of code. It’s up to you to explain how it work and why it’s may be easy or why those lines matter. 😀</p><p>Doing live coding is great. Take advantage of it to explain your shortcuts, what you faced, and why you do what you do.</p><p>It has been a tremendous opportunity for me the share a moment in front of an audience, doing live code. I hope you’ll remember few tips of this publications for your next talk. And I wish you the best!</p><p>💙 Thanks <a href="https://medium.com/decathlondigital">Decathlon Digital</a> for supporting me in this activity!</p><blockquote>Twitter : <a href="https://twitter.com/bapness">@bapness</a><br>YouTube : <a href="https://www.youtube.com/@baptistemobiledev">@baptistemobiledev</a><br><a href="https://www.linkedin.com/in/baptiste-carlier/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c176ae4b8a0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overlapping profile pictures with Jetpack Compose Modifier]]></title>
            <link>https://medium.com/@bapness/overlapping-profile-pictures-with-jetpack-compose-modifier-b91bc8693d21?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91bc8693d21</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[modifier]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 00:22:52 GMT</pubDate>
            <atom:updated>2023-03-15T00:22:52.740Z</atom:updated>
            <content:encoded><![CDATA[<p>Because a picture paints a thousand words, I guess with this one you will understand what I wanted to achieve when I started to work on a profile picture row :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*WV-DaCOUa4d8sL2xsChwDA.png" /></figure><p>I would like to display profile pictures in a way that they are overlapping above the previous. It’s not a recent design trend, but it’s still elegant for 2023.</p><blockquote>Main attributs:<br>- in light blue, the picture size with margin<br>- in pink, the negative spacing between pictures<br>- in green: margin of a picture</blockquote><p>Obviously it could be great to make the the result customizable with those attributs.</p><h3>Negative spacing</h3><p>Before beginning this small POC in Jetpack Compose, I knew that Row and Column composable functions allow negative arrangement.</p><p>Let’s use it and start a ProfilePicture composable at the same time :</p><pre>val size = 48.dp<br>val margin = 6.dp<br>val spacing = 12.dp<br><br>// Easy solution<br>Row(horizontalArrangement = Arrangement.spacedBy(-spacing.dp)) {<br><br>    list.forEachIndexed { index, item -&gt;<br>        val enable = index != (list.size - 1)<br>        ProfilePicture(<br>            url = item.url,<br>            imageSize = size,<br>            margin = margin.dp,<br>            negativeSpacing = spacing.dp,<br>            cropped = enable<br>        )<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*5ZnFb-X2f5GpUmW3tbrCFA.png" /></figure><p>Negative spacing: ok ☑</p><p>The profile pictures are overlapped and the last one is over the others. Great.</p><p>But so far you <strong>may not</strong> have learn anythings, and there’s no blank between items.</p><p>Let’s try to add…</p><h3>…Picture margin</h3><h4>👎 Using a border</h4><p>My first attempt to add margin was to encapsulate every pictures inside a Box with a Modifier.border(…).</p><pre>@Composable<br>fun WithBorder() {<br>    // Hard coded stuff<br>    val size = 48.dp<br>    val strokeSize = 4<br>    val containerColor = MaterialTheme.colorScheme.tertiary<br>    val avatarBackgroundColor = MaterialTheme.colorScheme.secondaryContainer<br>    Box(<br>        modifier = Modifier<br>            .border(<br>                border = BorderStroke(strokeSize.dp, containerColor),<br>                shape = CircleShape<br>            )<br>    ) {<br>        // This box represent the profile picture<br>        Box(<br>            modifier = Modifier<br>                .clip(CircleShape)<br>                .padding(strokeSize.dp)<br>                .background(<br>                    color = avatarBackgroundColor,<br>                    shape = CircleShape<br>                )<br>                .size(size)<br>        ) {}<br>    }<br>}<br><br>@Preview<br>@Composable<br>fun WithBorderPreview() {<br>    MaterialTheme {<br>        Row(<br>            horizontalArrangement = Arrangement.spacedBy(-16.dp),<br>        ) {<br>            (0..5).forEach {<br>                WithBorder()<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky48gfZjRpjzToMFkB9lWA.png" /></figure><p><strong>This solution is not cool for two reasons:</strong></p><p><strong>1 ) </strong>The border adds margin between items. It’s not a big issue because I can recalculate the result with the negative spacing.</p><p><strong>But</strong> it also add margin to the Row itself. 😏<br>I’ve tried to move the offset and update the bounds of the Row but it hasn’t been successful.</p><p><strong>2 ) </strong>The border is plain, not exclude. It means that the border color is displayed every time.</p><p>In case the background behind the Row isn’t known, or isn’t solid but gradient, this can be annoying.</p><p>I choose to skip this technical solution.</p><h4>👌 Drawing into the DrawScope</h4><p>The second option is to delete a negative part of every picture, except the last one.</p><p>With the three parameters (size, margin, spacing), I can place the perfectly sized circle to exclude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*YlIkjQqGqeDNY_qX4GbA0g.png" /></figure><p>For this purpose, I can use drawWithCache Modifier and onDrawWithContent method. They offer tools to display content over or under the modified composable.</p><p>This way, I can exclude the difference between the current profile picture and a second one where :</p><blockquote>center x = size.width * 1.5 — negativeSpacingPx<br>center y = size.height / 2<br>radius = size.width / 2 + marginPx</blockquote><p>The result is the combination of graphicalLayer Modifier and drawWithCache function like :</p><pre>.graphicsLayer {<br>    // Ensure BlendMode.Clear strategy works<br>    compositingStrategy = CompositingStrategy.Offscreen<br>}<br>.drawWithCache {<br>    val path = Path().apply {<br>        addOval(<br>            Rect(<br>                topLeft = Offset.Zero,<br>                bottomRight = Offset(size.width, size.height),<br>            ),<br>        )<br>    }<br>    onDrawWithContent {<br>        clipPath(path) {<br>            // this draws the actual image<br>            // if you don&#39;t call drawContent, it won&#39;t render anything<br>            this@onDrawWithContent.drawContent()<br>        }<br>        val marginRadius = size.width / 2f + marginPx<br>        val offset = size.width * 1.5f - negativeSpacingPx<br>        drawCircle(<br>            color = Color.Black,<br>            radius = marginRadius,<br>            center = Offset(x = offset, y = (size.height / 2f)),<br>            blendMode = BlendMode.Clear,<br>        )<br>    }<br>}</pre><p>I clip a path of the size of the content to render the circle that excludes the rounded portion.</p><p>Thanks the <a href="https://developer.android.com/jetpack/compose/graphics/draw/modifiers">official documentation</a> for the tips.</p><h3>Do it with a Modifier</h3><p>Finally, I can extract this into a Modifier extension in order to make it reusable. As result, I got 3 main elements.</p><h4><strong>The </strong><strong>Row itself with few parameters</strong></h4><ul><li>The (negative) spacing between pictures</li><li>The margin, which represent the border between two profile pictures</li><li>The image size</li></ul><h4><strong>The </strong><strong>ProfilePicture composable</strong></h4><p>It will use the three parameters + the url + a boolean in order apply to circle exclusion. As mentioned before, the last item will not be cropped.</p><p>I’m working with <a href="https://coil-kt.github.io/coil/compose/">Coil</a> to display image from URL.</p><p>Why do I chain Modifiers ? To make it more readable.<br>And because, once again, of the last item will only use the initialModifier.</p><h4><strong>The applyIf Modifier</strong></h4><p>Useful function to apply a Modifier in certain conditions. 🙂</p><h4>The circleMask Modifier</h4><p>Basically, you’ll find back elements see few lines ago.</p><p>Note that the size used inside the onDrawingWithContent is related to the current drawing environment. See drawWithCacheand CacheDrawScope documentation for more information.</p><h3>Please enjoy everything written right here ↓</h3><pre>// Usage :<br>val spacing = 4.dp<br>val margin = 2.dp<br>val imageSize = 32.dp<br><br>Row(horizontalArrangement = Arrangement.spacedBy(-spacing.dp)) {<br>    list.forEachIndexed { index, item -&gt;<br>        val enable = index != (list.size - 1)<br>        val url = item.thumbUrl<br>        ProfilePicture(<br>            url = url,<br>            imageSize = imageSize,<br>            margin = margin,<br>            negativeSpacing = spacing,<br>            cropped = enable,<br>        )<br>    }<br>}</pre><pre>@Composable<br>fun ProfilePicture(<br>    url: String,<br>    imageSize: Dp,<br>    margin: Dp = 0.dp,<br>    negativeSpacing: Dp = 0.dp,<br>    cropped: Boolean = false,<br>) {<br>   val initialModifier = Modifier<br>      .clip(CircleShape)<br>      .size(imageSize)<br>      .aspectRatio(1f)<br><br>   val marginPx = margin.dpToPx()<br>   val negativeSpacingPx = negativeSpacing.dpToPx()<br><br>   AsyncImage(<br>       modifier = initialModifier.applyIf(cropped) {<br>          circleMask(marginPx, negativeSpacingPx)<br>       },<br>       model = ImageRequest.Builder(LocalContext.current)<br>          .data(url)<br>          .crossfade(true)<br>          .build(),<br>      contentDescription = null,<br>      contentScale = ContentScale.Crop,<br>   )<br>}</pre><pre>fun Modifier.applyIf(<br>    condition: Boolean,<br>    modifierFunction: Modifier.() -&gt; Modifier,<br>) = this.run {<br>    if (condition) {<br>        this.modifierFunction()<br>    } else {<br>        this<br>    }<br>}</pre><pre>fun Modifier.circleMask(<br>    marginPx: Float,<br>    negativeSpacingPx: Float,<br>) = then(<br>    Modifier<br>        .graphicsLayer {<br>            // Ensure BlendMode.Clear strategy works<br>            compositingStrategy = CompositingStrategy.Offscreen<br>        }<br>        .drawWithCache {<br>            val path = Path().apply {<br>                addOval(<br>                    Rect(<br>                        topLeft = Offset.Zero,<br>                        bottomRight = Offset(size.width, size.height),<br>                    ),<br>                )<br>            }<br>            onDrawWithContent {<br>                clipPath(path) {<br>                    // this draws the actual image<br>                    // if you don&#39;t call drawContent, it won&#39;t render anything<br>                    this@onDrawWithContent.drawContent()<br>                }<br>                val marginRadius = size.width / 2f + marginPx<br>                val offset = size.width * 1.5f - negativeSpacingPx<br>                drawCircle(<br>                    color = Color.Black,<br>                    radius = marginRadius,<br>                    center = Offset(x = offset, y = (size.height / 2f)),<br>                    blendMode = BlendMode.Clear,<br>                )<br>            }<br>        },<br>)</pre><h3>Thanks for reading</h3><p>You can contribute in the comment section.<br>I may update this story later if we improve it together. 😉</p><ul><li>Twitter : <a href="https://twitter.com/bapness">@bapness</a></li><li>YouTube : <a href="https://www.youtube.com/@baptistemobiledev">@baptistemobiledev</a></li><li><a href="https://www.linkedin.com/in/baptiste-carlier/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91bc8693d21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deferred et awaitAll : comment paralléliser vos coroutines]]></title>
            <link>https://medium.com/@bapness/deferred-et-awaitall-comment-parall%C3%A9liser-vos-coroutines-5deedfafedc2?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5deedfafedc2</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[deferred]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[awaitall]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 16:31:00 GMT</pubDate>
            <atom:updated>2023-02-05T16:31:00.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deferred et awaitAll : comment paralléliser vos coroutines</h3><p>L’utilisation des coroutines est un standard pour gérer les tâches concurrentielles sur Android. Elles simplifient grandement le code exécuté de manière asynchrone et sa complexité.</p><p>Cela dit, les développeurs n’ont pas toujours connaissance des notions plus poussées permettant d’accélérer le traitement. Et c’est normal. Voici pourquoi.</p><p>En Clean Architecture, on a facilement ce type de découpe lorsqu’on a un <strong>écran “simple”</strong> :</p><ul><li><strong>1 écran simple</strong> utilise 1 ViewModel</li><li><strong>1 ViewModel</strong> utilise 1 UseCase</li><li><strong>1 UseCase</strong> utilise 1 Repository</li><li><strong>1 Repository</strong> utilise 1 DataSource</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4o4eyLtINoK_RDnhoiR83Q.png" /></figure><p>Grosso modo, il n’est pas toujours nécessaire d’avoir du parallélisme. 👌</p><p>Par contre, le principe d’un Usecase est aussi de pouvoir être réutilisables, notamment pour des écrans plus chargés comme des dashboards. On peut donc mettre en place un UseCase d’agrégation utilisant d’autres UseCases :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTyu2a5OHUffeaROg2M2mg.png" /></figure><p>Dans ce cas là, s’il n’y a pas d’adhérences entre ces UseCases, le parallélisme devient pertinent. Let’s go! ✨</p><h3>async/await</h3><p>Le pattern async/await de la librairie kotlinx.coroutines.core permet de ne pas attendre la fin de la réponse et de continuer le traitement.</p><p>Dans l’exemple ci-dessous, les 3 UseCases s’exécutent en parallèle. Ils sont lancés dans la lambda async qui retourne un Deferred typé par le retour du UseCase présent à l’intérieur.</p><pre>coroutineScope.launch {<br>    // Not blocking calls<br>    val alphaDeferred: Deferred&lt;Long&gt; = async { usecaseAlpha() }<br>    val betaDeferred: Deferred&lt;Long&gt; = async { usecaseBeta() }    <br>    val gammaDeferred: Deferred&lt;Long&gt; = async { usecaseGamma() }<br><br>    // Doing other stuff<br>    delay(1000)<br><br>    // Waiting for the end<br>    val alpha: Long = alphaDeferred.await()<br>    val beta: Long = betaDeferred.await()<br>    val gamma: Long = gammaDeferred.await()<br>}</pre><p>Il est possible de continuer à faire un traitement tant que la fin d’un Deferred n’est implicitement appelé avec await() (ou join()).</p><h3>awaitAll</h3><p>Au lieu d’appeler await() sur chaque Deferred, la méthode awaitAll() est aussi disponible sur <strong>une collection</strong> de Deferred. Pour cela, rien de plus simple que de lancer les async directement dans une liste :</p><pre>coroutineScope.launch {<br>    // Not blocking calls<br>    val deferreds: Deferred&lt;Long&gt; = listOf(<br>        async { usecaseAlpha() },<br>        async { usecaseBeta() },<br>        async { usecaseGamma() }<br>    )<br><br>    // Doing other stuff<br>    delay(1000)<br><br>    val complet = deferreds.awaitAll()<br>    // Waiting for the end<br>    val alpha: Long = complet[0]<br>    val beta: Long = complet[1]<br>    val gamma: Long = complet[2]<br>}</pre><p>Pratique dans le cas où tous les retours sont du même type. Un peu moins si ce n’est pas le cas.</p><p>Au cas échant, il faut caster manuellement les items de la liste. Et même si les appels se font en parallèle, parfois l’un avant l’autre, les items de la liste finale ici nommée complet sont dans le même ordre que la liste initiale deferreds.</p><p>💡 Ces outils sont simples mais pas assez souvent utilisés. Si vous êtes développeurs/développeuse, pensez y quand vous enchainerez des méthodes suspend un peu automatique. Et partagez ce type d’information à vos collègues. ;)</p><blockquote>- Twitter : <a href="https://twitter.com/bapness">@bapness</a><br>- YouTube : <a href="https://www.youtube.com/@baptistemobiledev">@baptistemobiledev</a><br>- <a href="https://www.linkedin.com/in/baptiste-carlier/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5deedfafedc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools and tips I wish I knew when I started Android development]]></title>
            <link>https://medium.com/@bapness/tools-and-tips-i-wish-i-knew-when-i-started-android-development-1dce73c491a?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dce73c491a</guid>
            <category><![CDATA[android-developers]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 20:49:09 GMT</pubDate>
            <atom:updated>2023-01-07T20:49:09.670Z</atom:updated>
            <content:encoded><![CDATA[<h4>I guess this very long title is self explanatory. 😃</h4><p>Just in case, I’m a fulltime Android developer since more than 4 years now. Step by step I’ve learned few things. It’s hard to remember everything because technologies move. But one of them is that we all need to help beginners.</p><p>Beginners offer new points of view and ideas. They’re shaping our projects, our teams and (kind of) the future of platform.</p><p>So I’ll try to give tips or tools, but of course first you may follow <a href="https://developer.android.com/guide">Android guidelines</a>. Use Jetpack librairies by default for example.</p><h3>JetBrains Toolbox</h3><blockquote>Manage your tools with ease</blockquote><p>You may know that Android Studio is based on IntelliJ IDEA. By default you can download Android Studio install software on Android Developer website. And each time you what to update, you’ll have to download the new version and re-download the install software.</p><p>To avoid this, JetBrains offer an its toolbox app which gives an easier way to track update and install them. Of course, there’s not just Android Studio but you can totally skip JetBrains IDEs.</p><p>There’s also a tab where you can find your most recent/bookmarked projects.</p><p>🔗 <a href="https://www.jetbrains.com/toolbox-app/">https://www.jetbrains.com/toolbox-app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRPbpQRXfQ35_37i1yViZg.png" /></figure><h3>Android codelabs</h3><blockquote>Guides, tutorials &amp; hands-on coding experience</blockquote><p>Google Codelabs offer a great opportunity to learn new things. You can update your skills about librairies you’re not up-to-date yet. They will guide you with the necessary documentation and code (<em>clonable</em> or starting from scratch)</p><p>Android Developer Relation team works hard to maintain it. So even if there’s still old topics, many of them are really recent.</p><p>It’s a great start for beginners and experimented contributors also. 🙂</p><p>🔗 <a href="https://codelabs.developers.google.com/?product=android">https://codelabs.developers.google.com/?product=android</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bby__7BERyeD7wBQmV-R1A.png" /></figure><h3>ADB Idea</h3><blockquote>Adds the ADB commands to Android Studio</blockquote><p>Bored to open the app settings manually on the device in order to clean and revoke the permissions for example ? This IDE plugin is for you!</p><p>It <strong>adds shortcuts</strong> directly in Android Studio to do those things fast. By far my favorite plugin.</p><p>I should give 5 stars and a good review right now!<br>EDIT: Done.</p><p>Also, the popup can be launch with shortcut to go even faster.</p><p>🔗 <a href="https://plugins.jetbrains.com/plugin/7380-adb-idea">https://plugins.jetbrains.com/plugin/7380-adb-idea</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*vHUUiMipLXAx4w_f.png" /></figure><h3>srccopy</h3><blockquote>Display and control your Android device</blockquote><p>A basic for me when I work on <strong>physical devices</strong>. This really small software helps mirroring the device on your computer. You’ll be able to use your mouse and your keyboard as inputs.</p><p>It uses ADB and is a great alternative of Android Studio Wifi pairing solution.</p><p>🔗 <a href="https://github.com/Genymobile/scrcpy](https://github.com/Genymobile/scrcpy)">https://github.com/Genymobile/scrcpy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*bMGLFn69QT-yIRt2" /></figure><h3>Timber</h3><blockquote>A logger with a small, extensible API which provides utility on top of Android’s normal Log class.</blockquote><p>This is a logger provides utility on top of Android’s normal Log class.</p><p>It helps avoid logging in production because of its setup and because you’ll replace every Log call by Timber call.</p><p>🔗 <a href="https://github.com/JakeWharton/timber">https://github.com/JakeWharton/timber</a><br>🔗 KMM alternative: <a href="https://github.com/AAkira/Napier">https://github.com/AAkira/Napier</a></p><h3>Options: Open files… / Always Select…</h3><p>Damn! When I reinstall Android Studio, every time I activate those two options.</p><p>You’ll navigate faster into the project files and so understandard faster an existing project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*NejtnDQj3jfktiakepRhRg.png" /></figure><h3>GitKraken</h3><blockquote>Includes an intuitive Git GUI &amp; powerful Git CLI</blockquote><p>When you have to deal with git, this client is really visual.</p><p>This desktop client helps understand where branches are. Which one is working on. It helps fetching or cherry-pick. 🍒</p><p>You can plug it to GitHub or GitLab. Enjoy managing you merge-request or pull-request also inside the client. See the tags. Use GitHub Actions right inside it also.</p><p>Sadly*, it’s free for open-source projects only. But if you want to use it in your company, you can go to GitKraken Entreprises plan.</p><p>*<em>️ but understandable</em></p><p>🔗 <a href="https://www.gitkraken.com/">https://www.gitkraken.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f1wX-YWhFruZVYoE.png" /></figure><h3>Now In Android</h3><blockquote>A fully functional Android app built entirely with Kotlin and Jetpack Compose</blockquote><p>UI, Architecture, modularization, testing, … the promise of this repository is to build something at the state of the art of the Android development.</p><p>It’s in work in progress. I guess it will be eternally in WIP. But you can clone it and learn how the best practices are set up. A reference for any developer who wants to stay up-to-date.</p><p>🔗 <a href="https://github.com/android/nowinandroid">https://github.com/android/nowinandroid</a></p><p>By the way, Google has already published other apps on GitHub. Like Google I/O or Android Summit apps.<br>It’s a good idea to go snooping source code of great apps, when it’s available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81B30y02Hd2Oe1Kt.png" /></figure><h3>Material Symbols</h3><p>Also known as <em>Google Material Icons</em>, this set of icons is a standard.</p><p>If your project don’t have a design system or at least a designer, you will quickly need this resource. You’ll be able to download PNG or SVG for your app. And take time to find the right one, because there are over 2,500 glyphs.</p><p>Like this, your app will be a little more attractive. And maybe your users (or your team) will enjoy it much better.</p><p>🔗 <a href="https://fonts.google.com/icons?icon.platform=android">https://fonts.google.com/icons?icon.platform=android</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj18IXkdKVC9U70mVU-_QA.png" /></figure><h3>Android roadmap</h3><blockquote>The Android Developer Roadmap suggests learning paths to understanding Android development.</blockquote><p><strong>Now In Android</strong> (NIA) is nice. But there’s also a lot of other stuff to know. I might say, “a path” that every developer can take to know how to dev for Android.</p><p>Because NIA is focusing on the last guideline, it’s not covering HOW a lot of apps are legacy built.</p><p>This time it’s really REALLY exhaustive. You don’t need to learn everything from this roadmap but at least knowing that there’re alternatives.</p><p>🔗 <a href="https://github.com/skydoves/android-developer-roadmap">https://github.com/skydoves/android-developer-roadmap</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbxbYuBQ8a7xfMvys0uGbA.png" /></figure><h3>Android Developers on YouTube</h3><blockquote>Get the latest Android news, best practices, live videos, demonstrations, tutorials, and more!</blockquote><p>It seems a bit obvious, but @<a href="https://medium.com/u/e1f26db83092">Android Developers</a> YouTube channel is full of great videos. You’ll get anything you want about tools, development, librairies. Perfect to learn things already done in the past, and news about incoming Android features.</p><p>Don’t forget to subscribe and activate the notifications. Also Kotlin YouTube channel is pretty interesting.</p><p>🔗 <a href="https://www.youtube.com/c/AndroidDevelopers">https://www.youtube.com/AndroidDevelopers</a><br>🔗 <a href="https://www.youtube.com/Kotlin">https://www.youtube.com/Kotlin</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90FM5eHfLFL6vAiXyrKWmg.png" /></figure><h3>Social networks and blog websites</h3><p>And finally, a good place to learn stuff or ask questions might be on social networks and blog websites.</p><p>By the time, I’ve created my own Twitter list on Android developers. Reading this specific feed helps me discovering threads and hot topics.</p><p>Slack communities are another fantastic option.<br>By the way, <a href="https://android-dev-france.slack.com/">French Slack</a> is nice. 🇫🇷</p><p>Ans lastly, on those blogging platforms you’ll find really nice content. Don’t forget to check the posting date and the comments also.</p><ul><li>🔗 <a href="https://proandroiddev.com/">https://proandroiddev.com/</a></li><li>🔗 <a href="https://dev.to/t/android">https://dev.to/t/android/</a></li><li>Medium of course 😅</li></ul><h3>Thanks for reading</h3><p>If you reach that line, thanks. I hope it helps you. I mixed different kind of tips, tools, or links. Like this you can be geared up. And also you can look up a bit because Android is continuously evolving.</p><p>If you’re beginner and found this post useful, give a clap 👏.<br>You can contribute in the comment section. 😉</p><ul><li>Twitter : <a href="https://twitter.com/bapness">@bapness</a></li><li>YouTube : <a href="https://www.youtube.com/@baptistemobiledev">@baptistemobiledev</a></li><li><a href="https://www.linkedin.com/in/baptiste-carlier/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dce73c491a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Remote Config + coroutine ?]]></title>
            <link>https://medium.com/@bapness/firebase-remote-config-coroutine-9335b5db386c?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9335b5db386c</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[firebase-remote-config]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 17:25:38 GMT</pubDate>
            <atom:updated>2021-06-09T17:25:38.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>Firebase Remote Config + coroutine ?</h3><h4>En voulant mettre en place Firebase Remote Config en place sur un projet, quelques questions sont apparues…</h4><h3>Quand récupérer la config ?</h3><p>D’abord, on va se mettre d’accord rapidement, dans la majeure partie des cas, il faut <strong>récupérer</strong> les données distances (remote) au lancement de l’application.</p><p>La question est de savoir :</p><h3>Quand appliquer cette config distante dans la config locale ?</h3><p>Et bien là, éternelle réponse : ça dépend. 😁</p><ul><li><strong>La Remote Config doit-elle être utilisée toute de suite ?</strong></li></ul><p>On peut imaginer pour des raisons de sécurités, de légalité ou marketing, qu’il faille appliquer la configuration distante <strong>au plus vite</strong>. Sinon on peut l’utiliser plus tard si rien de presse.</p><ul><li><strong>On peut utiliser la Remote Config plus tard : comme au prochain lancement ?</strong></li></ul><p>À la limite là, <strong>c’est vous qui voyez</strong>.</p><p>Soit plus tard au prochain lancement en gardant la config en cache de l’instance RemoteConfig.</p><p>Soit plus tard dans le parcours de l’utilisateur mais <strong>en s’assurant que le changement de configuration est acceptable</strong>. Si par exemple vous aller charger des données ou faire un affichage en fonction de la configuration, est-ce acceptable d’avoir un changement de configuration entre temps ? Est-ce qu’il y a un risque d’incohérence quelque part ?</p><ul><li><strong>On veut utiliser la Remote Config tout de suite. Comment ?</strong></li></ul><p>En attendant que la callback fetchAndActivate() de récupération des données soit complète pour la charger dans la config locale et l’utiliser.</p><figure><img alt="Suspendre la callback permet d’attendre la synchronisation de l’instance &amp; d’avoir des données local synchronisées avec la remote." src="https://cdn-images-1.medium.com/max/1024/1*hY3CMOIK_2nZnmyZfILqsg.png" /></figure><p>Suspendre la callback permet d’attendre la synchronisation de l’instance Remote Config.</p><p>En suite, on charge les données de l’instance Remote Config dans la configuration locale synchronisées. <em>Et voilà !</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9ab2436509fcb1ee028d39f196a1bb/href">https://medium.com/media/0d9ab2436509fcb1ee028d39f196a1bb/href</a></iframe><p>L’inconvénient est d’avoir un chargement au lancement de l’app. Mais au moins les données seront fraîches.</p><p>On peut aussi mettre délai de <em>time out</em> des requêtes de Firebase Remote Config pour s’assurer de ne pas (pas plus) détériore l’UX.</p><p>Retrouvez un peu plus de code sur le <a href="https://github.com/BapNesS/android-sample-firebaseremoteconfiguration"><strong>repo GitHub associé</strong></a> où différentes méthodes sont implémentées.</p><p>N’hésitez pas à 👏 applaudir ce billet et à le partager 📨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9335b5db386c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy way to Toast with ViewModel, LiveData & a bit of abstraction]]></title>
            <link>https://medium.com/@bapness/easy-way-to-toast-with-viewmodel-livedata-a-bit-of-abstraction-e00f074e0004?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e00f074e0004</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 07:31:01 GMT</pubDate>
            <atom:updated>2020-02-12T07:37:54.192Z</atom:updated>
            <content:encoded><![CDATA[<p>Few days ago, I’ve started working on a new Android application built with Kotlin.</p><p>As usual, I’ve created an Activity and replaced every button behavior by Toasts only to focus on primary step of design.</p><blockquote>FYI: Toasts &amp; snackbars provide brief messages about app processes at the bottom of the screen.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqFbkg5pUJfP1Ovbr0aNMA.jpeg" /></figure><p>I was doing the same thing on multiple places in ViewModels. So, I’ve tried to find a simpler way to manage thoses Toasts.</p><h3>Event&lt;T&gt; : handle message from ViewModel</h3><p>Dealing event messages with standard LiveData is not good.</p><p>As mentionned in “ <a href="https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150">LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)</a> ”, a more beautiful way to handle thoses messages is to use the <a href="https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java">SingleLiveEvent</a> class or the <a href="https://gist.github.com/JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af">Event class</a> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2b1248ff48a1427468ad8e8671839f5/href">https://medium.com/media/e2b1248ff48a1427468ad8e8671839f5/href</a></iframe><p>I choose this solution. This way, the message is wrapped into a class that manage the message usage to <strong>only provide it once</strong>.</p><h3>An abstract BaseViewModel</h3><p>The aim of this BaseViewModel is to:</p><ul><li>Manage the Event into a LiveData</li><li>Provide methods to set/post a value into this Event</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70496c989806b39426f660ccf6b9b33d/href">https://medium.com/media/70496c989806b39426f660ccf6b9b33d/href</a></iframe><p>With the beauty of abstraction, in the UsableViewModel we can just use setValue (or postValue) methods to push message to the view that is observing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa8feab9c34496c1ad326a77c5fa9709/href">https://medium.com/media/fa8feab9c34496c1ad326a77c5fa9709/href</a></iframe><h3>An abstract BaseActivity</h3><p>Last thing to do is to provide a nice UsableViewModel in the Activity. For this, you need an abstract Activity class :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/842b85ab862270ceae072c4d5fd7423e/href">https://medium.com/media/842b85ab862270ceae072c4d5fd7423e/href</a></iframe><p>This BaseActivity can provide the right ViewModel. Its initObservers() method deals with the fact of displaying the message.</p><p>Now in our UsableActivity we can manage only what we need :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dd6e2e53eb0686f43b74f29eb976db7/href">https://medium.com/media/2dd6e2e53eb0686f43b74f29eb976db7/href</a></iframe><p>In this particular sample, I used binding. But it’s not the main purpose.</p><p>What you need to see are the ViewModel properties and the calls for provideViewModel() and super.iniObservers() methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBcM6DfwALT5dRrT9xBYSQ.png" /><figcaption>“Base” classes are abstract</figcaption></figure><p>I almost forgot this extension to toast:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e80170a6c8d67e47f5dfe783b7bc910/href">https://medium.com/media/3e80170a6c8d67e47f5dfe783b7bc910/href</a></iframe><p>You can totally do it with Fragments if you need. And if you want to go deeper, it can be done withSnackbar but with few changes.</p><p>Don’t forget to comment if you want to share your experience.<br>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e00f074e0004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Création d’une app pour la cantine (partie 4/4)]]></title>
            <link>https://medium.com/@bapness/cr%C3%A9ation-dune-app-pour-la-cantine-partie-4-4-3d1710e97652?source=rss-716fc12c2b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1710e97652</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Baptiste Carlier]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 11:10:29 GMT</pubDate>
            <atom:updated>2020-01-19T11:10:44.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Article précédent :<br>⬅️ <a href="https://medium.com/p/f4b4cdd67a6c">Design 🖌️</a></p><p>Après une période de tests auprès de quelques parents sur le Play Store en beta test, on me remonte quelques évolutions possibles.</p><p>Je mets tout ça dans mon board <em>Projects</em> sur GitHub et prépare doucement la migration en même temps. Laissez-moi vous expliquer :</p><h3>4. Migration et release 🎁</h3><h4>Migration Play Store et Firebase</h4><p>Initialement j’ai publié l’app sur mon compte développeur Google et avec mon projet Firebase.</p><p>L’organisme de gestion de l’école et moi sommes d’accord pour qu’elle soit publiée sur un compte de l’école. Donc il faut transférer à la fois :</p><ul><li>L’application, d’un compte développeur à l’autre</li><li>Les données, d’un compte Google-Firebase à l’autre</li></ul><p>Si vous cherchez <strong>la manipulation pour transférer une application</strong>, c’est ici :<br><a href="https://support.google.com/googleplay/android-developer/answer/6230247?hl=en">https://support.google.com/googleplay/android-developer/answer/6230247?hl=en</a><br>C’est simple et assez rapide.</p><p><strong>Pour les données Firebase, ce n’est pas compliqué non plus.</strong> Les connexions se font à l’aide du fichier <strong>google-services.json</strong>. Le plus désagréable est de récupérer les données d’un Firestore pour les ajouter sur l’autre. L’interface ne permet pas d’importer/d’exporter les données sous forme de fichier par exemple. Mais c’est fait.</p><h4>Un dernier petit coup de pinceau</h4><p>Je profite de la prochaine release pour ajouter quelques fonctionnalités telles que :</p><ul><li>Un <strong>ViewPager2</strong> pour passer d’un menu à l’autre pour rapidement</li><li>Une <strong>BottomNavigationView</strong> avec <a href="https://medium.com/@naththeprince/delightful-animations-in-android-d6e9c62a23d3">des petites animations</a> en <strong>VectorDrawable</strong></li><li>Un onglet d’accès au site web de l’<a href="http://www.ecolesaintpierredascq.fr/lapplication-android-de-saint-pierre-dascq/?utm_source=Medium&amp;utm_medium=Article&amp;utm_campaign=2019_01">école Saint-Pierre d’Ascq</a> et quelques tags de campagne Google Analytics</li><li>Un tutoriel de présentation après le launch screen</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xGbcDQ6tYQO14YeBFQsUg.png" /></figure><h4>L’architecture à cette dernière étape :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uHDDrM6tZX3kpkGpGT9fg.png" /></figure><p>Côté admin, il suffit simplement d’ajouter les menus dans Firestore et les jours d’école sur le Raspberry Pi tous les deux à trois mois. C’est léger car assez peu fréquent à faire et à moitié automatisé (donc encore manuel).</p><blockquote>La question qu’on me pose beaucoup est de savoir comment je lis le fichier PDF pour intégrer les données : à la main pour l’instant. C’est là la dernière action manuelle. Mais je vais essayer de contacter <a href="https://www.api-restauration.com/">API Restauration</a> pour essayer de récupérer les données sous un autre format. Et si ce n’est pas possible, voir avec les <em>Firebase Cloud Fonction</em> pour analyser le PDF de façon totalement automatique.</blockquote><p>À l’avenir, je voudrais aussi, intégrer un planning des réunions ou évènements de l’école, mettre des notifications quand des articles sont publiés sur le site de l’école, ou intégrer un onglet <a href="https://www.educartable.com/">Educartable</a> si cela intéresse les parents.</p><h4><strong>Si vous voulez télécharger l’application, </strong><a href="https://play.google.com/store/apps/details?id=com.baptistecarlier.android.ecolesaintpierredascq"><strong>elle est sur le Play Store</strong></a><strong>.</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fd5pGYhWb3T1Hyyl8OB%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fd5pGYhWb3T1Hyyl8OB&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fd5pGYhWb3T1Hyyl8OB%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="236" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc40319d8d8418780491433756c2fc03/href">https://medium.com/media/fc40319d8d8418780491433756c2fc03/href</a></iframe><h3>Les articles :</h3><p>1️⃣ <a href="https://medium.com/p/790a4b01ac78">Données &amp; stockage via Firebase Cloud Firestore 📦</a><br>2️⃣️ <a href="https://medium.com/p/15e1c57da4af">Notifications via FCM 🔔</a><br>3️⃣ <a href="https://medium.com/p/f4b4cdd67a6c">Design 🖌️</a><br>➡️ <a href="https://medium.com/p/3d1710e97652">Publication sur le Play Store et migration 🎁</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1710e97652" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>