<?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 Mihai Batista on Medium]]></title>
        <description><![CDATA[Stories by Mihai Batista on Medium]]></description>
        <link>https://medium.com/@mihai-batista?source=rss-862818773af4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WcboPM56GrBqpeWA</url>
            <title>Stories by Mihai Batista on Medium</title>
            <link>https://medium.com/@mihai-batista?source=rss-862818773af4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:38:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihai-batista/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[Give a Voice to Your LLM]]></title>
            <link>https://itnext.io/give-a-voice-to-your-llm-99f6b70d55bc?source=rss-862818773af4------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f6b70d55bc</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Mihai Batista]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 12:43:35 GMT</pubDate>
            <atom:updated>2026-01-24T19:10:38.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI ENGINEERING</h4><h4>From Sluggish to Seamless: Building Zero-Lag Voice Agents with Cartesia</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJxk7uMSvD4GQ4N7_rNKdA.png" /><figcaption>Futuristic illustration showing data streaming from a glowing digital brain representing an LLM, through Cartesia TTS, and immediately transforming into a glowing audio waveform representing real-time speech output.</figcaption></figure><p>The “Latency Gap” has always been the final boss of conversational AI. We’ve all experienced it: you speak to an AI, there’s a three-second pause while the brain “thinks,” and then a robotic voice reads the generated text. To build an agent that actually feels alive, you need to solve two things simultaneously: <strong>latency</strong> and <strong>naturalness</strong>.</p><p>Cartesia’s Sonic engine is designed to kill the delay. With a time-to-first-audio (TTFA) as low as <strong>40ms</strong>, it is fast enough to keep up with human speech patterns in real time. But speed is only half the battle; if the AI sounds disjointed or lacks the correct intonation, the immersion breaks. Achieving a truly human-like flow requires a specific architecture, one that leverages <strong>input streaming</strong> to feed text into the TTS before the LLM has even finished its sentence, while carefully managing <strong>prosody</strong> through stateful WebSocket contexts.</p><p>In this guide, we’ll look at how to bridge the gap between your LLM and your users by building a real-time, bidirectional voice pipeline using Cartesia’s Sonic-3 model.</p><h3>What You’ll Learn</h3><p>In this guide, we aren’t just going to look at API documentation. We are going to build a high-performance audio pipeline from the ground up. By the end of this article, you will understand:</p><ul><li><strong>The Streaming Architecture:</strong> How to transition from a “request-response” mindset to a bidirectional WebSocket flow.</li><li><strong>Contextual Prosody:</strong> Why Cartesia’s context object is the secret to making the AI voice have flow and maintain prosody.</li><li><strong>Advanced Control Flow:</strong> How to use continue_, flush(), and no_more_inputs() to handle real-time LLM token streams.</li><li><strong>Production Configurations:</strong> Selecting the right sample rates and raw encodings to ensure your frontend can play audio the millisecond it arrives.</li></ul><h3>Cartesia TTS: The Core Integration</h3><p>Cartesia’s SDK provides both HTTP and WebSocket interfaces, but for ultra-low latency streaming, we’ll use WebSockets.</p><h4>Why Streaming Matters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC1A08B6K1shC_yFzFZsuw.png" /><figcaption>A technical diagram illustrating the real-time, ultra-low latency voice AI pipeline. It shows the parallel data flow: User Audio input flows to Speech-to-Text (STT), which streams tokens to a Large Language Model (LLM), which in turn streams tokens directly to the Cartesia TTS WebSocket, finally resulting in a streaming audio byte output.</figcaption></figure><p>The key to natural-sounding AI conversations isn’t just the quality of the voice, it’s the timing. Here’s what makes Cartesia special:</p><p><strong>Traditional approach:</strong><br>- Generate complete text response (2–5 seconds)<br>- Send to TTS and synthesize complete audio (1–3 seconds)<br>- <strong><em>Total delay: 3–8 seconds</em></strong></p><p><strong>Cartesia’s streaming approach:</strong><br>- Generate text tokens as they arrive (streaming)<br>- Stream text chunks to Cartesia in real-time<br>- Receive audio bytes immediately as each chunk is processed<br><strong><em>- First audio: 40–90ms</em></strong></p><h4>The Secret Sauce: Text Streaming &amp; “Continuations”</h4><p>The main technical hurdle with streaming TTS is <strong>prosody</strong>. If you send words one by one to a traditional TTS, it treats every word like a full sentence, resulting in robotic, disjointed speech.</p><p>Cartesia solves this with <strong>continuations</strong>. By using a context, you can stream text chunks (or even single tokens) to their WebSocket API. The model maintains the &quot;state&quot; of the conversation, ensuring that the intonation and rhythm remain natural as new text arrives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpIjWqsN5PCiRa7yePK7og.png" /><figcaption>A visual comparison diagram contrasting TTS outputs. The left side, labeled “Traditional TTS,” shows fragmented, disjointed audio waveforms labeled “robotic, ‘chopped up’ speech.” The right side, labeled “Cartesia with Continuations,” displays a single, smooth, flowing audio waveform labeled “natural, connected prosody.”</figcaption></figure><h4>Setting Up Cartesia</h4><p>First, install the Cartesia Python SDK:</p><pre>pip install cartesia</pre><h4>The Streaming Implementation</h4><p>Here’s the detailed Cartesia integration that handles bidirectional streaming:</p><pre>import asyncio<br>from cartesia import AsyncCartesia<br>from typing import AsyncIterator<br><br>class CartesiaTTS:<br>    def __init__(self, api_key: str):<br>        self.client = AsyncCartesia(api_key=api_key)<br>        self.voice_id = &quot;f786b574-daa5-4673-aa0c-cbe3e8534c02&quot;  # Katie - stable, realistic<br>        self.model_id = &quot;sonic-3&quot;<br>        self.output_format = {<br>            &quot;container&quot;: &quot;raw&quot;,<br>            &quot;encoding&quot;: &quot;pcm_s16le&quot;,<br>            &quot;sample_rate&quot;: 16000,<br>        }<br>    <br>    async def stream_tts(<br>        self, <br>        text_stream: AsyncIterator[str]<br>    ) -&gt; AsyncIterator[bytes]:<br>        &quot;&quot;&quot;<br>        Convert a stream of text chunks into a stream of audio bytes.<br>        <br>        This is where the magic happens - text goes in, audio comes out,<br>        all in real-time with minimal buffering.<br>        <br>        Args:<br>            text_stream: Async iterator yielding text chunks from LLM<br>            <br>        Yields:<br>            Audio bytes in the configured format (pcm_s16le, 16kHz)<br>        &quot;&quot;&quot;<br>        # Create a WebSocket connection to Cartesia<br>        ws = await self.client.tts.websocket()<br>        <br>        try:<br>            # Start the streaming context<br>            ctx = ws.context()<br>            <br>            async def send_text():<br>                &quot;&quot;&quot;Coroutine that sends text chunks to Cartesia&quot;&quot;&quot;<br>                async for text_chunk in text_stream:<br>                    # Send each text chunk as it arrives from the LLM<br>                    await ctx.send(<br>                        model_id=self.model_id,<br>                        voice_id=self.voice_id,<br>                        transcript=text_chunk,<br>                        continue_=True,  # Keep the stream open for more text<br>                        **self.output_format<br>                    )<br>                <br>                # Signal that we&#39;re done sending text<br>                await ctx.no_more_inputs()<br>            <br>            # Run text sending and audio receiving concurrently<br>            send_task = asyncio.create_task(send_text())<br>            <br>            # Receive and yield audio chunks as they arrive<br>            async for output in ctx.receive():<br>                audio_chunk = output.get(&quot;audio&quot;)<br>                if audio_chunk:<br>                    # Audio bytes are ready - send them immediately!<br>                    yield audio_chunk<br>            <br>            # Ensure the send task completes<br>            await send_task<br>            <br>        finally:<br>            # Clean up the WebSocket connection<br>            await ws.close()</pre><h4>Key Implementation Details</h4><p>Let’s break down what makes this streaming efficient:</p><p><strong>1. Bidirectional streaming: </strong>We send text chunks and receive audio chunks simultaneously using asyncio.create_task(). The LLM generates text → we immediately send it to Cartesia → Cartesia immediately returns audio.</p><p><strong>2. The <em>continue_</em> parameter: </strong>This tells Cartesia whether more text is coming. Set it to True for all the text chunks except the last one.</p><p><strong>3. WebSocket context:</strong> The ctx = ws.context() creates a streaming context that manages the bidirectional communication. Each context represents one complete TTS generation session.</p><p><strong>4. Minimal buffering:</strong> Notice we yield audio bytes immediately as they arrive in the async for output in ctx.receive() loop. No waiting for complete sentences or paragraphs.</p><h3>Context Lifecycle Management</h3><p>Cartesia contexts have an important lifecycle that you need to manage properly. Understanding the <em>continue</em> parameter and context finalization methods is crucial for building robust streaming applications, so let’s dive deeper on this topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQH8LP65pj9gYjKagP7l6A.png" /><figcaption>A state transition diagram illustrating the Cartesia WebSocket context lifecycle. It shows the primary “Open Context (Streaming)” state, which loops back on itself during send(text, continue=True) or flush() operations, and transitions to the final &quot;Closed Context&quot; state only upon receiving a no_more_inputs() signal.</figcaption></figure><h4>1. The continue Flag: Maintaining the Flow</h4><p>You’ll use the continue_ parameter (note the underscore to avoid conflicts with Python’s reserved keyword).</p><ul><li><strong>When to use it:</strong> Set continue_=True for every chunk of text that isn&#39;t the absolute end of the LLM&#39;s response.</li><li><strong>What it does:</strong> It tells the Sonic model: <em>“Don’t drop your intonation yet. More words are coming.”</em> Without this, the model might lower its pitch at the end of a word, making it sound like the end of a sentence even if it’s just a pause in the LLM’s generation.</li><li><strong>The Golden Rule:</strong> If you are streaming from an LLM word-by-word, continue_ should be True until the LLM yields its final token.</li></ul><h4>2. ctx.flush(): The &quot;Force Play&quot; Button</h4><p>Sometimes the internet lags, or your LLM takes a second to think mid-sentence. If you don’t want the user to hear a strange gap, you can call flush().</p><ul><li><strong>The Mechanism:</strong> A flush tells the engine: <em>“I’m still planning to send more later, but generate audio for everything I’ve sent so far, immediately.”</em></li><li><strong>Flush IDs:</strong> Each time you call flush, Cartesia increments a flush_id. The audio bytes coming back will include this ID, which is a lifesaver if you need to track which specific text transcript generated which segment of audio.</li></ul><h4>3. ctx.no_more_inputs(): The Final Signal</h4><p>This is your “End of Transmission” flag. It is the definitive signal that the context can be closed.</p><ul><li><strong>When to use it:</strong> Call this exactly once per response, immediately after the LLM stream is exhausted.</li><li><strong>The Result:</strong> It allows the model to perform a “final wrap-up” of the prosody, perfecting the downward inflection that signals a finished thought and then gracefully shuts down the WebSocket context.</li></ul><h3>Models and Language Support: Going Global</h3><p>To build a truly international product, your TTS needs to handle more than just standard English. Cartesia’s <strong>Sonic</strong> family is designed with a “Multilingual-First” approach, meaning the same high-quality prosody carries over across different regions.</p><h4>1. Available Models</h4><p>When initializing your stream, you can target specific versions of the Sonic engine:</p><ul><li>sonic-3 — <strong>Flagship.</strong> High-fidelity and complex emotion.</li><li>sonic-turbo — <strong>Performance.</strong> Maximum speed for quick chats.</li><li>sonic-2 — <strong>Legacy Stability.</strong> Standard multi-lingual apps.</li></ul><blockquote><strong><em>🚀 Pro-Tip:</em></strong><em> If you want the latest stable features without manual updates, use the base </em><em>sonic-3 ID. For production consistency, you can pin a specific snapshot like </em><em>sonic-3-2025-10-27.</em></blockquote><h4>2. Global Language Coverage</h4><p>Sonic-3 currently supports <strong>42+ languages</strong>, covering roughly 95% of the world’s most spoken tongues. You don’t select the language directly instead, <strong>language is determined by the voice you choose</strong>. Each voice in Cartesia’s library is associated with a specific language and accent.</p><p>For example:<br>- Brooke (English US): `e07c00bc-4134–4eae-9ea4–1a55fb45746b`<br>- Yumiko (Japanese): `2b568345–1d48–4047-b25f-7baccf842eb0`<br>- German voices, Spanish voices, Mandarin voices, etc.</p><h3>Optimizing the Output: Formats &amp; Sample Rates</h3><p>The output_format configuration is where you win the battle against latency.</p><ul><li><strong>Encodings:</strong> While mp3 or wav are common, they introduce overhead. For streaming, use <strong>pcm_s16le</strong> (Signed 16-bit Little Endian). It is the standard for raw audio and requires zero decoding on the frontend just pipe it into an audio buffer.</li><li><strong>Sample Rates:</strong> * <strong>16000Hz:</strong> The “Sweet Spot” for AI agents. It captures full speech bandwidth but keeps data size small.</li><li><strong>24000Hz — 44100Hz:</strong> Use these for “Studio Quality” or music-heavy applications.</li></ul><blockquote><strong><em>🚀 Pro Tip for Max Performance:</em></strong><em> Always use the </em><strong><em>raw</em></strong><em> container with </em><strong><em>16000Hz pcm_s16le</em></strong><em>. By bypassing the transcoding and headers of MP3/WAV, you save valuable milliseconds on both the server and the client.</em></blockquote><h3>Key Takeaways</h3><p>Building a world-class voice interface isn’t just about picking the “smartest” LLM; it’s about architecting a pipeline where data never stops moving. Here is what you should remember when integrating Cartesia into your stack:</p><ul><li><strong>Streaming is a Requirement, Not an Option:</strong> To hit sub-100ms latency, you must bypass the traditional “request-response” cycle. Use WebSockets to pipe LLM tokens into Cartesia as they are generated, rather than waiting for full sentences.</li><li><strong>The Power of Stateful Context:</strong> Cartesia’s .context() is what separates &quot;robotic&quot; AI from human-like conversation. By reusing a context for an entire response, the model maintains prosody, ensuring the AI doesn&#39;t sound like it&#39;s starting a new thought with every text chunk.</li><li><strong>Signaling is Your Best Friend:</strong> Master the three-way handshake of continue_, flush(), and no_more_inputs(). These flags give you granular control over when the model should &quot;look ahead&quot; for more text versus when it should finalize a sentence with a natural downward pitch.</li><li><strong>PCM Over Compressed Formats:</strong> In high-concurrency voice agents, every millisecond of decoding counts. Stick to raw <strong>pcm_s16le</strong> or <strong>pcm_f32le</strong> at <strong>16000Hz</strong> or <strong>24000Hz</strong>. This allows your frontend to play the audio immediately without the overhead of parsing MP3 headers or WAV containers.</li><li><strong>Choose the Model for the Mission:</strong> Use <strong>Sonic-3</strong> for applications requiring deep emotional range and multilingual support, but switch to <strong>Sonic-Turbo</strong> if your absolute priority is the fastest possible “Time to First Byte” (TTFB) in simple dialogue.</li></ul><h3>Final Thoughts</h3><p>Ultra-low latency TTS is the bridge that turns a standard chatbot into a presence. By using Cartesia’s streaming architecture, you aren’t just reducing lag, you’re removing the “uncanny valley” of silence that often plagues AI interactions.</p><p>Give it a try, your users (and their ears) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f6b70d55bc" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/give-a-voice-to-your-llm-99f6b70d55bc">Give a Voice to Your LLM</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Place Scope Handling on Auto-Pilot with Koin & Compose Navigation]]></title>
            <link>https://proandroiddev.com/place-scope-handling-on-auto-pilot-with-koin-compose-navigation-d40023b1ba6f?source=rss-862818773af4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40023b1ba6f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[koin]]></category>
            <dc:creator><![CDATA[Mihai Batista]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 18:20:00 GMT</pubDate>
            <atom:updated>2024-10-04T18:20:00.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Work smarter, not harder, when managing custom Koin scopes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SJ1T1qEVuB0yXzIs" /><figcaption>Photo by Jigar Panchal on Unsplash</figcaption></figure><p>Koin has straightforward APIs to manage custom scopes and Compose Navigation can easily express app flows as nested navigation graphs, but how can we connect these two worlds to automatically connect to a scope when the user enters a flow and close it when that flow is exited? Read along if this sparked your interest.</p><p>This article assumes that you are familiar with the following two topics; in case they are new to you, you can quickly get up to speed by visiting the linked resources:</p><ul><li><em>Koin custom scopes— </em><a href="https://insert-koin.io/docs/reference/koin-core/scopes"><em>https://insert-koin.io/docs/reference/koin-core/scopes</em></a></li><li><em>Nested navigation graphs in Compose — </em><a href="https://developer.android.com/guide/navigation/design/nested-graphs#compose"><em>https://developer.android.com/guide/navigation/design/nested-graphs#compose</em></a></li></ul><h3><strong>Scope &amp; Navigation Definition</strong></h3><p>For the solution described in this article we will make use of one convention in order to make a logical bridge between app flows and scopes and that is: <strong><em>the route of a nested nav graph is used as scope identifier.</em></strong></p><p>We start by describing our nested nav graph and here please pay attention to the declared route, we will use it again in the next step when declaring the scope tied to this flow.</p><pre>const val ROUTE_GRAPH_FLOW: NavGraphRoute = &quot;route_graph_flow&quot;<br><br>/**<br> * Navigation graph of the custom flow.<br> */<br>fun NavGraphBuilder.flowNavGraph(<br>    navController: NavController,<br>) {<br>    navigation(<br>        startDestination = routeScreen1.getRouteWithPlaceholders(),<br>        route = ROUTE_GRAPH_FLOW,<br>    ) {<br>        screen1(<br>            onNextClick = {<br>                navController.navigateToScreen2()<br>            }<br>        )<br>        screen2(<br>            onFinishFlowClick = {<br>                navController.navigateToStart()<br>            }<br>        )<br>    }<br>}</pre><p>As you can see below, the definition of the scoped dependencies comes with no surprises. The important aspect to be noticed here is that the name of the scope qualifier is the route we have declared above, to fulfil our convention.</p><pre>val scopeModule = module {<br><br>    /**<br>     * Dependencies of [ROUTE_GRAPH_FLOW] scope.<br>     */<br>    scope(named(ROUTE_GRAPH_FLOW)) {<br><br>        viewModel {<br>            Screen1ViewModel(<br>                flowRepository = get(),<br>            )<br>        }<br><br>        // add other viewModels<br><br>        scoped&lt;FlowRepository&gt; {<br>            FlowRepositoryImpl(<br>                authRepository = get()<br>            )<br>        }<br>        <br>        // add other repositories, use cases, DAOs        <br>    }<br>}</pre><blockquote>⚡ <strong>Quick Refresher:</strong> A dependency coming from a narrow scope can rely on a dependency coming from a larger one, but vice-versa is not possible. If we want to inject a scoped repository, the viewModel that makes use of it has to be also scoped. That’s why in the definition above the viewModel is declared alongside the repository and is not placed in the root scope.</blockquote><h3><strong>Injecting Scoped Dependencies</strong></h3><p>The setup is ready, now we are moving to the injection of our scoped dependencies. We inject the dependency that is highest in our architectural layers and that is the viewModel.</p><p>For this purpose, koinViewModel is the API we are looking for. Its signature reveals two relevant aspects for our solution. Firstly, it takes a scope as parameter, so injecting a viewModel tied to route_graph_flow scope is a breeze and looks like this:</p><pre>val scope = koinInstance.getOrCreateScope(<br>                 scopeId = &quot;route_graph_flow&quot;,<br>                 qualifier = named(&quot;route_graph_flow&quot;)<br>            )<br>            <br>val viewModel: ScopedViewModel = koinViewModel(<br>     scope = scope<br>)</pre><p>And secondly, the default value of the scope parameter is LocalKoinScope.current. This is brilliant because it allows us to implicitly pass a scope using the <a href="https://developer.android.com/develop/ui/compose/compositionlocal">CompositionLocal</a> mechanism.</p><h3>The solution</h3><p>We’re moving to the final part of writing the composable that is taking care of the scope management, we will call it AutoConnectKoinScope. Now let’s look at the details.</p><p>navController.addOnDestinationChangedListener() is the key of the solution, as it gives us the current destination (screen) and implicitly the nested nav graph (flow) that the destination is part of. Adding our convention in the equation enables us to know which scope should be used to resolve the dependencies of a particular screen.</p><blockquote>🔓 Key API: addOnDestinationChangedListener gives us the current destination (screen) and implicitly the nested nav graph (flow) that the destination is part of.</blockquote><p>For clarity I’ve broke the solution into three parts:</p><ul><li><strong>1st —</strong> For each visited screen the appropriate scope is resolved and passed implicitly through <a href="https://developer.android.com/develop/ui/compose/compositionlocal">CompositionLocal</a> mechanism.</li></ul><pre>if (currentNavGraphRoute != null) {<br>       val scopeForCurrentNavGraphRoute = koinInstance.getOrCreateScope(<br>            scopeId = currentNavGraphRoute,<br>            qualifier = named(currentNavGraphRoute)<br>       )<br>       scopeToInject = scopeForCurrentNavGraphRoute<br>} else {<br>       scopeToInject = rootScope<br>}<br>            <br> .....<br> <br> CompositionLocalProvider(<br>      LocalKoinScope provides scopeToInject,<br>      content = content<br> )</pre><blockquote><strong>💡 Good to Know:</strong> We don’t need to link a custom scope to the root scope, by default dependencies coming from the root scope can be resolved in a custom scope.</blockquote><ul><li><strong>2nd —</strong> The previous scope is closed when we detect that the user has moved to a new flow.</li></ul><pre>val currentNavGraphRoute = destination.parent?.route<br>val previousNavGraphRoute = lastKnownNavGraphRoute<br><br>if (previousNavGraphRoute != null &amp;&amp; currentNavGraphRoute != previousNavGraphRoute) {<br>      val lastScope = koinInstance.getOrCreateScope(<br>            scopeId = previousNavGraphRoute,<br>            qualifier = named(previousNavGraphRoute)<br>      )<br>      lastScope.close()<br>}      </pre><ul><li><strong>3rd —</strong> The correct scope is restored in case the parent activity is being recreated, for this purpose we store the last known nav graph route in a global variable (in order to be kept around while the process lives) and use it to initialise the mutable state that holds the scope to be injected.</li></ul><pre>var scopeToInject by remember {<br>        val lastKnownNavGraphRoute = lastKnownNavGraphRoute<br>        mutableStateOf(<br>            value = if (lastKnownNavGraphRoute != null) {<br>                koinInstance.getOrCreateScope(<br>                    scopeId = lastKnownNavGraphRoute,<br>                    qualifier = named(lastKnownNavGraphRoute)<br>                )<br>            } else {<br>                rootScope<br>            }<br>        )<br>    }</pre><p>To keep things clean &amp; tidy we make use of DisposableEffect to unregister the OnDestinationChangedListener when AutoConnectKoinScope composable leaves the composition.</p><blockquote>🍬 <strong>Koin for</strong> <strong>Compose Goodies: </strong>To get a hold of the current Koin instance, Koin provides us with the getKoin() composable, and to get the current scope with LocalKoinScope.current .</blockquote><p>To have visibility over the entire navigation and be able to manage the scope for any screen of the app, we need to place the AutoConnectKoinScope composable at the top of our Compose hierarchy, somewhere above the app&#39;s NavHost.</p><p>And that’s it folks 🎉, with this last piece we’ve placed the scope management on auto-pilot and we can move our focus on other aspects of the app craftsmanship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40023b1ba6f" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/place-scope-handling-on-auto-pilot-with-koin-compose-navigation-d40023b1ba6f">Place Scope Handling on Auto-Pilot with Koin &amp; Compose Navigation</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[Sonarqube Reporting in a Multi-Module Android Project]]></title>
            <link>https://mihai-batista.medium.com/sonarqube-reporting-in-a-multi-module-android-project-fd29c45a0040?source=rss-862818773af4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd29c45a0040</guid>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mihai Batista]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 20:08:42 GMT</pubDate>
            <atom:updated>2021-08-09T20:08:42.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Pain-Free Sonarqube Setup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vtZvrLvocTyzK33h" /><figcaption>Photo by <a href="https://unsplash.com/@dawson2406?utm_source=medium&amp;utm_medium=referral">Stephen Dawson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey there! 👋 I might now your pain; there are plenty of good examples out there when it comes to Sonarqube for single module apps but not that many when it comes to multi-modules. This post describes swiftly a very common use case, check the <strong>Goal section</strong> to see if it matches the use case you are trying to achieve.</p><h3>Goal</h3><p>Centralise Jacoco coverage results &amp; Detekt results of each sub-module <strong>in a single Sonarqube project.</strong></p><h3>Setup</h3><p>To centralise the results<strong> the key is to have a single Sonarqube instance, </strong>this instance needs to be declared in the <strong>project_root/build.gradle</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/910b208277a29c0188bc6978c7fea928/href">https://medium.com/media/910b208277a29c0188bc6978c7fea928/href</a></iframe><p><strong><em>Tip:</em></strong><em> To keep the root </em><em>build.gradle clean you can place the Sonarqube related code in a separate </em><em>sonar.gradle file.</em></p><p><strong>The solution lies in the lines 23–26 and 27–30, have a closer look, through these lines we tell Sonarqube which Jacoco and Detekt reports to publish.</strong></p><p>At this point the Sonarqube setup is complete, make sure that Jacoco and Detekt are properly setup in each sub-module build.gradle and properly generate the respective XML reports. If that’s working, you are ready to publish to Sonarqube.</p><h3>Publish to Sonarqube</h3><p><strong>Run Detekt and Jacoco Gradle tasks,</strong> once they finish, make sure the XML reports are correctly generated in the build/reports folder of each module.</p><p>If the reports are present, run .gradlew sonarqube and you are done. Check the result in the Sonarqube web platform.</p><p>I hope you found it helpful, if you have any questions and feedback please let me know via the comments section.</p><p>Stay positive &amp; healthy; see you on the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd29c45a0040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Scopes with Dagger 2]]></title>
            <link>https://medium.com/geekculture/feature-scopes-with-dagger-2-2b7a2ceb1c7d?source=rss-862818773af4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7a2ceb1c7d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Mihai Batista]]></dc:creator>
            <pubDate>Sun, 16 May 2021 12:07:30 GMT</pubDate>
            <atom:updated>2021-05-18T21:46:33.818Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scope Mechanics and How We Can Build any Kind of Scopes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K5hkmPNj7msWKyAl" /><figcaption>Photo by <a href="https://unsplash.com/@lastnameeaster?utm_source=medium&amp;utm_medium=referral">La-Rel Easter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>App, activity &amp; fragment scopes are familiar constructs when working with Dagger, but often enough we find ourselves in need of scopes that don’t match any of those. In those cases we need to create custom scopes. Their lifetime spans over multiple fragments and/or activities and usually maps to the lifetime of features. That’s why we will call them feature scopes in this article.</strong></p><h3>All Scopes Are the Same</h3><p>All Dagger scopes use the same mechanics and before getting to feature scopes we start by looking into the familiar app scope (usually defined through <strong>AppComponent — @Singleton</strong>). This gives us a great insight into scope’s main constructs and puts us on the right track to understand how to setup &amp; use them. First, let’s revise three important constructs:</p><h3><strong>1. Scope Annotation</strong></h3><p>Scope annotation gives the name of the scope and is the glue between dependencies and components. In the Android community the <em>de facto</em> <strong>app scope</strong> annotation is @Singleton.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043a37020250523248774eba7a5125d2/href">https://medium.com/media/043a37020250523248774eba7a5125d2/href</a></iframe><blockquote><strong>Let’s bust a wide spread myth: “</strong>Only by annotating classes with @Singleton it will make the injected dependencies singletons at app level”<strong> — False.</strong></blockquote><p>@Singleton<strong> is a regular annotation </strong>and<strong> </strong><em>per se </em>it doesn’t do more than labelling dependencies and components. Based on this labelling, Dagger understands what is the relation between them. Its wide spread use can be attributed to being the only scope annotation provided out-of-the-box by <strong>javax</strong> library and being used in the vast majority of Dagger examples. Since there’s no magic behind it, it can be very well exchanged with any other annotation, personally I prefer to use @AppScope , which I find more expressive.</p><h3><strong>2. Components &amp; Subcomponents Definition</strong></h3><p>Components and subcomponents are the Dagger constructs in charge of injecting dependencies. A component that injects app wide dependencies is typically called <strong>AppComponent</strong> and a base implementation of it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c27566245b7dd9947df57b8ceaaaebf/href">https://medium.com/media/8c27566245b7dd9947df57b8ceaaaebf/href</a></iframe><p>An important aspect to be noticed is the use of the @Singleton annotation. <strong>An</strong> <strong>instance of AppComponent can inject only dependencies that are scoped — singletons (through @Singleton) or unscoped — non-singletons.</strong> This is a key aspect in understanding scopes, to visualise this better let’s have a look at the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*KSZK6EaVJkXp5csXlpwe0g.png" /><figcaption>Scoped and unscoped dependencies</figcaption></figure><p>The above example follows the typical use of the AppComponent ; a single instance of AppComponent@78d8e81 is created during the app lifetime and it is stored in the app instance. This component instance is in charge of injecting the scoped <strong>FilesRepository</strong> and unscoped <strong>GeoLocationRepository</strong> dependencies into three ViewModels constructors. As a result, we can see that the scoped <strong>FilesRepository</strong> was injected as a singleton (all the injected dependencies having the same @86c9c02 reference), and for the unscoped <strong>GeoLocationRepository</strong> each injection resulted in a new instance being created.</p><blockquote>A component/subcomponent instance can inject dependencies that are either scoped to the component/subcomponent scope (singletons) or unscoped dependencies (non-singletons).</blockquote><h3>3.<strong> Place of Component/Subcomponent Instance Creation &amp; Its Lifetime</strong></h3><p>In case of the app scope the AppComponent is initialised in the app class and lives as long as the app lives. By controlling the component instance lifetime &amp; having dependencies as singletons or non-singletons in the context of the component instance lifetime, we can control the life of dependencies as desired.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da283f0e94e1430881382ce19e16d8ef/href">https://medium.com/media/da283f0e94e1430881382ce19e16d8ef/href</a></iframe><blockquote>By controlling the initialisation of the component / subcomponent we control the scope.</blockquote><blockquote>Quick recap, the constructs needed for scopes setup are:</blockquote><blockquote>- Scope annotation</blockquote><blockquote>- Component / subcomponent definition</blockquote><blockquote>- Place of component / subcomponent initialisation &amp; its lifetime</blockquote><p>In the next section we’ll look how these three constructs apply to feature scopes.</p><h3>Feature Scopes</h3><p>To illustrate the setup and use of feature scopes we will use a concrete example.</p><p><strong>UX requirements — </strong>for a train ticket app we would like to implement a ticket booking feature. The booking flow consists of four screens: route selection, filling of personal data, summary of the purchase and the confirmation screen. The user can navigate back and forward in the flow, is able to see the data that he filled-in and the collected data is discarded when the user exits the flow. BookingRepository stores the data collected during the flow and represents the source of truth for computing the flow state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*uXPPXRiaddRAL4XdSr4Wsw.png" /><figcaption>High level class diagram for the booking flow</figcaption></figure><p>To implement the flow with the above requirements we want a Dagger setup which allows us to inject a new BookingRepository instance when the flow is started, inject the same BookingRepository instance during the flow and discard the BookingRepository instance when the flow is terminated. These requirements call for a <strong>feature scope</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*cO9mVH5RvSxBOMo6lMLYqQ.png" /><figcaption>Scopes overview</figcaption></figure><p>In the above setup the AppComponent injects dependencies that live at app level, the BookingFlowSubcomponent injects dependencies that live during the booking flow and the activity subcomponent injects dependencies that have their lifetime tied to the one of the activity.</p><p>An important aspect to be considered here is that all injectors apart from AppComponentare implemented as subcomponents. Subcomponents have access to all dependencies exposed by their parents and ancestors up to the root component.</p><p>The components graph looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*NZxha83vv0Mmnw_smkVpiw.png" /></figure><p><strong><em>Tip: </em></strong><em>An easy way to tell Dagger to create subcomponents for activities with a certain scope is through </em><em>@ContributesAndroidInjector and </em><em>scope annotations.</em></p><p><em>The following snippet shows how to create the </em><em>RouteActivitySubcomponent — @ActivityScope :</em></p><pre>@ActivityScope <br>@ContributesAndroidInjector(modules = RouteSelectionModule::class)<br>abstract fun contributeRouteSelectionActivity(): RouteSelectionActivity</pre><p><strong><em>Note:</em></strong><em> Subcomponents for the other activities are created in the same manner.</em></p><h3>Setup</h3><p>All scopes follow the same mechanics. We’ve seen previously the most important constructs in the light of the AppComponent <strong>— </strong>@Singleton, let’s see now how they apply to <strong>feature scopes</strong>.</p><p><strong>1. Scope annotation </strong>— same implementation, just a different name, BookingFlowScope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d68b2d2b1ee099ace230b65ac6e42c62/href">https://medium.com/media/d68b2d2b1ee099ace230b65ac6e42c62/href</a></iframe><p><strong><em>Scoped dependencies </em></strong>— to have BookingRepository injected as singleton in the context of the booking flow scope, the class needs to be annotated with @BookingFlowScope .</p><pre>@BookingFlowScope<br>internal class BookingRepositoryImpl @Inject constructor(<br>    private val apiInteractor: ApiInteractor,<br>    private val paymentRepository: PaymentRepository<br>)</pre><p><strong><em>Unscoped dependencies</em></strong> — view models need to be unscoped, for them a new instance has to be created with every injection, so they are not annotated with @BookingFlowScope. <strong><em>Side note:</em></strong><em> In case of view models, the activities’s view model store is in charge of providing the same instance when the activity is being recreated after a configuration change.</em></p><p><strong>2. Subcomponent — </strong>for the feature scope we will use a subcomponent in order to access all dependencies exposed by its parent AppComponent and link the modules that provide dependencies specific for this scope. The subcomponent uses the @BookingFlowScope created in the previous step and is able to inject all the activities of the flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3caf3542e921fc2fc107bb98219c3d32/href">https://medium.com/media/3caf3542e921fc2fc107bb98219c3d32/href</a></iframe><p><strong>3. Place of subcomponent instance creation &amp; it’s lifetime</strong></p><p>When setting up a subcomponent there is <strong>one additional step</strong> compared to the AppComponent (which is the root of the component graph). We need to tell Dagger how is this component connected with the rest of the graph. In our example, BookingFlowSubcomponent is a child of the AppComponent. To express this relation we add the following lines in the <strong>AppComponent.kt</strong> file:</p><pre><em>/**<br> * Get [BookingFlowSubcomponent].<br> */<br></em>fun bookingFlowSubcomponent(): BookingFlowSubcomponent</pre><p><strong>The additional step is now done</strong> and we can focus on the subcomponent instance creation and its lifetime. The logic for manipulating the BookingFlowComponent instance resides in the App class in the methods <strong>getOrCreateBookingFlowSubcomponent</strong> and <strong>releaseBookingFlowSubcomponent</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73daced1d7836527bec5153a2de7aeb2/href">https://medium.com/media/73daced1d7836527bec5153a2de7aeb2/href</a></iframe><p><strong>getOrCreateBookingComponent</strong> method is used in all screens of the flow to get a handle over a BookingFlowSubcomponent instance. When called in the first screen it creates a new instance of theBookingFlowSubcomponent and caches it in the bookingFlowSubcomponent class variable. For the subsequent calls, executed in the other screens, the method will return the cached instance.</p><p><strong>releaseBookingFlowComponent</strong> method is used when exiting the booking flow in order to close the scope. To close the scope, the subcomponent is set to null . In the next garbage collection cycle the subcomponent instance and the injected dependencies will be disposed. A new subcomponent instance will be created when the flow is started again.</p><h3>Use &amp; Injection</h3><p>To highlight the usage of BookingFlowSubcomponent inside of activities we will take a look at RouteSelectionActivity (usage in the other activities is identical):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e07e41b252eca3da19904f59973f1479/href">https://medium.com/media/e07e41b252eca3da19904f59973f1479/href</a></iframe><p>There are two interesting lines in the code above, <strong>line 4 and 13</strong>.</p><p>In <strong>line 4</strong>, before calling the constructor of the base class, two things happen:</p><ol><li>appInstance.getOrCreateBookingFlowSubcomponent() returns a new instance of BookingFlowComponent because RouteSelectionActivity is the first screen of the flow. In the other screens or when RouteSelectionActivity is revisited, it will return the same instance.</li><li>bookingFlowSubcomponent.inject(this) injects dependencies for this activity. During the flow, the injection of dependencies is always done in the context of the same BookingFlowSubcomponent instance.</li></ol><p>In <strong>line 13</strong>, when the flow is terminated, the BookingFlowSubcomponent is released. The BookingFlowSubcomponent instance will be garbage collected in the next cycle; that’s also true for the injected dependencies since nobody keeps references to them anymore.</p><p>And that’s it folks, thank you very much for reading! I hope you found it helpful, if you have any questions and feedback please let me know via the comments section.</p><p>Stay positive &amp; healthy; see you on the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7a2ceb1c7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/feature-scopes-with-dagger-2-2b7a2ceb1c7d">Feature Scopes with Dagger 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>