<?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 Dikenmaharjan on Medium]]></title>
        <description><![CDATA[Stories by Dikenmaharjan on Medium]]></description>
        <link>https://medium.com/@dikenmaharjan10?source=rss-51077e499cd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MxZcXKiHiuEVL1cg</url>
            <title>Stories by Dikenmaharjan on Medium</title>
            <link>https://medium.com/@dikenmaharjan10?source=rss-51077e499cd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:12:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dikenmaharjan10/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[How Structured Concurrency Happens in Kotlin]]></title>
            <link>https://medium.com/@dikenmaharjan10/how-structured-concurrency-happens-in-kotlin-0262c20d4315?source=rss-51077e499cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0262c20d4315</guid>
            <category><![CDATA[cancellations]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dikenmaharjan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 10:15:51 GMT</pubDate>
            <atom:updated>2026-06-09T18:41:16.890Z</atom:updated>
            <content:encoded><![CDATA[<p>From CoroutineScope to how cancellation really works — the machinery underneath every launch { }</p><p>Tags: kotlin, coroutines, structured-concurrency, internals</p><h3>It all starts with a scope</h3><p>Every coroutine you launch starts life inside a CoroutineScope. So before anything else, it&#39;s worth asking what a scope actually is - and the answer is a bit anticlimactic:</p><pre>public interface CoroutineScope { <br>  val coroutineContext: CoroutineContext<br>}</pre><p>That’s it. That’s the entire interface. A scope is nothing but a wrapper around one CoroutineContext. Which means the first thing to internalize is dead simple:</p><blockquote><em>If you’ve got a scope, you’ve got a </em><em>CoroutineContext. The scope is just the thing holding it.</em></blockquote><p>And here’s the catch — everything interesting about structured concurrency actually lives in that context, not the scope. So the question we really need to answer is: what <em>is</em> a CoroutineContext?</p><h3>A CoroutineContext is just a map</h3><p>Honestly? You can think of a CoroutineContext as a <strong>map of key → value pairs</strong>. That&#39;s the mental model that&#39;ll carry you the furthest. The types are a little specific though, so let&#39;s pin them down:</p><ul><li><strong>Key</strong> — CoroutineContext.Key&lt;E&gt;, where E is the kind of element the key points to.</li><li><strong>Value</strong> — CoroutineContext.Element, and every element knows its own key:</li></ul><pre>public interface CoroutineContext { <br><br>  public operator fun &lt;E : Element&gt; get(key: Key&lt;E&gt;): E?<br><br>  public interface Key&lt;E : Element&gt; // the key<br><br>  public interface Element : CoroutineContext { // the value<br>    public val key: Key&lt;*&gt; <br>  }<br><br>}</pre><p>Reading from a context is just a keyed lookup: context[SomeKey] returns the one element stored under that key, or null if there isn&#39;t one. And it&#39;s type-safe - the key is parameterized as Key&lt;E&gt;, so the compiler already knows the result is an E. No iterating, no casting.</p><p>So a context is really just a typed bag of elements. Before we crack one open, it’s worth asking what they’re actually <em>for</em> — because each well-known element controls one slice of how a coroutine behaves.</p><h3>Keys define how the coroutine behaves</h3><p>The elements in a context aren’t just metadata sitting in a map — they decide how your coroutine behaves. Each of the well-known keys owns one dimension of that behavior:</p><ul><li><strong>CoroutineDispatcher</strong> - Dispatchers.IO, Default, Main (key: ContinuationInterceptor.Key) - which thread or thread pool the coroutine runs on.</li><li><strong>Job</strong>(key: the Job companion object) - lifecycle, cancellation, parent/child structure.</li><li><strong>CoroutineExceptionHandler</strong> (key: CoroutineExceptionHandler.Key) - what happens to uncaught exceptions.</li><li><strong>CoroutineName</strong> (key: CoroutineName.Key) - a human-readable name, for debugging and logging.</li></ul><p>So when you write:</p><pre>scope.launch { /* this block is the coroutine */ }</pre><p>…that block you hand to launch <em>is</em> the coroutine - and how it behaves comes entirely from the key→value pairs in the context of the scope you launched it from. Should it run on a background thread? The dispatcher in the context decides. Should it have a name in the logs? The CoroutineName decides. The coroutine itself doesn&#39;t carry any behavior around with it; it just reads what to do out of the context it was handed.</p><h3>Anatomy of an element: CoroutineName</h3><p>We’ve seen what coroutine context elements do. Now let’s open one up and see how it’s built. The nice thing is that once you’ve understood the simplest element, you’ve pretty much understood them all — they all follow the same basic pattern.</p><p>Let’s start with CoroutineName. It&#39;s about as simple as it gets. Its only job is to attach a label to a coroutine for debugging. If coroutine debugging is enabled, that label shows up in thread names and stack traces, making it easier to tell which coroutine is doing what. If debugging is disabled, it doesn&#39;t affect execution in any way.</p><p>So CoroutineName is really just a name tag. Nothing fancy. But its implementation is important because it follows the exact same structure you&#39;ll see in every other coroutine context element.</p><pre>public data class CoroutineName( <br>  val name: String<br>) : AbstractCoroutineContextElement(CoroutineName) {<br><br>    public companion object Key : CoroutineContext.Key&lt;CoroutineName&gt;<br><br>    override fun toString(): String = &quot;CoroutineName($name)&quot; <br><br>}</pre><blockquote><strong><em>Wait — what’s that </em></strong><strong><em>(CoroutineName) argument?</em></strong><em> It looks like the class passing itself in, but it isn&#39;t. In expression position (inside the parentheses), a bare class name resolves to its </em><strong><em>companion object</em></strong><em>, and </em><em>CoroutineName&#39;s companion </em>is<em> its </em><em>Key. So </em><em>AbstractCoroutineContextElement(CoroutineName) is just a shorter way of writing </em><em>AbstractCoroutineContextElement(CoroutineName.Key) - &quot;store my own companion as my key.&quot; It&#39;s the same resolution that later lets </em><em>context[CoroutineName] find this element: the key you store and the key you look up by are the same object.</em></blockquote><p>Three details are worth pausing on, because Job, CoroutineExceptionHandler, and the dispatchers all repeat them:</p><ol><li><strong>The companion object is the key.</strong> companion object Key : CoroutineContext.Key&lt;CoroutineName&gt; declares a single shared key for the whole program - the one Key instance used everywhere this element is stored or looked up.</li><li><strong>It extends </strong><strong>AbstractCoroutineContextElement.</strong> That base class does almost nothing on its own:</li></ol><pre>public abstract class AbstractCoroutineContextElement( <br>    public override val key: Key&lt;*&gt; <br>) : Element</pre><p>It just implements the Element interface - which, recall, <em>is</em> a CoroutineContext. So an element inherits all the map behavior ( get, fold, plus) for free, and the only thing it has to supply is its key - the (CoroutineName) you saw above.</p><p>Strip it down and every element is the same thing: a small data holder that extends AbstractCoroutineContextElement and carries a companion object as its singleton key.</p><h3>Combining elements: the + operator</h3><p>A single element is already a context — a context of one. To get a context of several, you join them with +. And because every element is itself a CoroutineContext, they all share the same plus operator, governed by a single rule: <strong>same key replaces.</strong> A context never holds two elements under one key, so merging two contexts that share a key keeps the right-hand value and drops the left:</p><pre><br>// Both names share CoroutineName.Key, so &quot;worker&quot; replaces &quot;loader&quot;.<br>// ctx holds two elements: Dispatchers.IO and CoroutineName(&quot;worker&quot;).<br>val ctx = Dispatchers.IO + CoroutineName(&quot;loader&quot;) + CoroutineName(&quot;worker&quot;)</pre><p>Under the hood, plus is just a fold of the right-hand context into the left:</p><pre>public operator fun plus(context: CoroutineContext): CoroutineContext {<br>  return if (context === EmptyCoroutineContext) {<br>    this // nothing to add <br>  } else {<br>    context.fold(this) { acc, element -&gt; // for each element on the right... <br>      val removed = acc.minusKey(element.key) // drop any same-key element from acc <br>      if (removed === EmptyCoroutineContext){ <br>        element <br>      } else {<br>        // (the real impl also pins the dispatcher to the tail - see below)<br>        CombinedContext(removed, element) // then append the new one<br>      }<br>    }<br>  }<br>}</pre><p>Two helpers do all the work:</p><ul><li><strong>minusKey(key)</strong> returns the context with the element under that key removed. The <em>remove-then-append</em> on each step is the &quot;same key replaces&quot; rule made literal - the old value is evicted before the new one is added, so duplicates can&#39;t happen.</li><li><strong>CombinedContext(rest, element)</strong> is the internal multi-element type: a linked list of &quot;rest + one element at the head.&quot; A single element is the base case; each + grows the chain by one.</li></ul><p>Tracing the earlier line through it:</p><pre>start: Dispatchers.IO (1 element)<br> + CoroutineName(&quot;loader&quot;) = CombinedContext(IO, Name(&quot;loader&quot;)) (2 elements)<br> + CoroutineName(&quot;worker&quot;): CombinedContext(IO, Name(&quot;worker&quot;)) (still 2 - replaced &quot;loader&quot;))</pre><p>Name(&quot;worker&quot;) survives only because it shares CoroutineName.Key with Name(&quot;loader&quot;).</p><p>One real-world detail before moving on: plus deliberately keeps the dispatcher ( ContinuationInterceptor) pinned at the <em>tail</em> of the chain. It&#39;s a performance choice - the dispatcher is looked up on every suspend and resume, so the library keeps it where lookups are cheapest, no matter where you wrote it. The resulting context behaves identically either way.</p><h3>So how does this context get passed around?</h3><p>This is the part that feels like magic until someone shows you the trick. A coroutine buried three suspend calls deep can just ask for coroutineContext and get back the <em>right</em> one - even though nobody ever passed it down by hand. How?</p><p><strong>The suspend functions are doing it for you.</strong> When the Kotlin compiler sees a suspend function, it quietly rewrites the signature, slipping in one extra parameter: a Continuation. So a function you wrote like this:</p><pre>suspend fun fetchUser(id: String): User</pre><p>compiles down to roughly this on the JVM:</p><pre>fun fetchUser(id: String, continuation: Continuation&lt;User&gt;): Any?</pre><p>And a Continuation isn&#39;t just some callback - it&#39;s carrying the context along with it:</p><pre>public interface Continuation&lt;in T&gt; { <br>    public val context: CoroutineContext // &lt;-- right here <br>    public fun resumeWith(result: Result&lt;T&gt;) <br>}</pre><p>So once it’s compiled, every suspend function already has the CoroutineContext in hand - tucked inside that hidden Continuation. When your code reads the coroutineContext property, the compiler just reaches into the continuation and pulls it out. And that context is the very one from the scope you launched in, quietly riding along through every suspend call you make.</p><p>The whole mechanism in a sentence: <strong>the scope’s context hitches a ride inside the </strong><strong>Continuation that every suspend function secretly receives - so any coroutine, anywhere down the chain, can read it and act on it.</strong></p><h3>The special one: Job</h3><p>Most keys just tune <em>how</em> a coroutine runs — what thread, what name. But one key plays a completely different role: Job. It&#39;s the key that owns the coroutine&#39;s whole lifecycle - and the part we&#39;ll dig into here, its <strong>cancellation</strong>.</p><p>When you call scope.launch { }, the builder spins up a fresh Job for that coroutine and drops it into the context the block runs with (same key replaces, remember - so the new Job just takes over the Job slot). From that point on, the Job <em>is</em> your handle to the coroutine&#39;s life: you can ask if it&#39;s still active, wait for it to finish, or - the interesting bit - cancel it.</p><p>There are <strong>two</strong> Job objects involved:</p><pre>// (1) The scope already carries a Job - this is the PARENT. <br>val parentJob = scope.coroutineContext[Job] <br><br>// (2) launch creates ONE new Job - the CHILD - and returns it. <br>val childJob = scope.launch {<br>    // (3) Inside the block, the context&#39;s Job is that SAME child object. <br>    check(coroutineContext[Job] === childJob) // identical object <br>} <br>check(childJob.parent === parentJob) // child points back to parent</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3aaiZiAD8K4G9pkyY7ieQ.png" /></figure><p>The reference launch <em>returns</em> and the Job <em>inside</em> the block feel like two different things, but they&#39;re the <strong>same child object</strong> - launch just hands you a pointer to it and also slots it into the block&#39;s context. The only genuinely separate Job is the <strong>parent</strong>, the one that was already sitting in the scope. The child keeps a .parent pointer back to it, and that single pointer is the whole parent/child link.</p><p>So let’s actually follow what happens when you cancel one. It’s not what most people assume.</p><h3>Nesting builds a tree</h3><p>That parent→child link isn’t a one-off — it repeats on every launch. A coroutine launched <em>inside</em> another coroutine&#39;s block becomes a child of <em>that</em> coroutine&#39;s Job. So nesting launch calls builds a whole tree:</p><pre>val job = scope.launch {        // child of the scope&#39;s Job…<br>    launch { downloadA() }      // and is the parent of these two launched coroutines.<br>    launch { downloadB() }<br>}</pre><p>That’s three Jobs across two levels:</p><ul><li>the scope’s Job <em>(the root here)</em></li><li>job — the outer launch, a child of the scope</li><li>downloadA — a child of job</li><li>downloadB — a child of job</li></ul><p>Each inner launch does the exact two-Job dance from above, just one level down: it reads the current Job out of its block&#39;s context (here, job), creates a fresh child, and links the two.</p><p>And it keeps going. A launch inside one of <em>those</em> children produces a <strong>grandchild</strong> — and naming each Job makes the lineage obvious:</p><pre>val parent = scope.launch {            // parent.parent     == the scope&#39;s Job<br>    val child = launch {               // child.parent      == parent<br>        val grandchild = launch {      // grandchild.parent == child<br>            cleanup()<br>        }<br>    }<br>}</pre><p>Each launch returns the Job it created, so parent, child, and grandchild here are just those three Jobs, by name. Follow their .parent pointers and you can read the whole lineage straight off: grandchild → child → parent → the scope&#39;s Job. grandchild sits two levels below parent — which is exactly what makes it a <em>grand</em>child.</p><p>Nothing new happens at each step; it’s the same parent/child move repeated. So the tree runs as deep as your code nests — every node holding a .parent pointer up, and its parent holding a reference back down.</p><p>That tree <em>is</em> the “structured” in structured concurrency — it’s the structure. And it’s what lets a single cancel() at any node reach everything beneath it, which is exactly where we&#39;re headed next.</p><h3>cancel() doesn’t stop anything</h3><p>Here’s the first surprise: calling cancel() on a Job <strong>doesn&#39;t stop your code.</strong> It can&#39;t, really - there&#39;s no safe way to forcibly freeze a running thread halfway through an instruction. So all cancel() does is two tiny things:</p><ol><li>Flip the Job’s state to <strong>Cancelling</strong>..</li><li>Store the <strong>cause</strong> — a CancellationException — that it will later throw into the coroutine.</li></ol><p>And then… your coroutine just keeps running. Cancellation is a <em>request</em>, not a kill switch.</p><h3>The signal is just an exception</h3><p>So how does the running code ever actually stop? Through a thrown CancellationException. There&#39;s no exotic control-flow primitive hiding here - cancellation is plain old exception unwinding. The Job is holding onto that cancellation cause, and the next chance the coroutine gets, the exception is thrown into it.</p><h3>“The next chance” means a suspension point</h3><p>This is the cooperative part, and it’s the whole game. Every suspending function the library gives you — delay, yield, withContext, await, channel sends and receives - peeks at the Job&#39;s state when it suspends or resumes. If the Job has gone into Cancelling, then instead of resuming like normal, that suspension point <strong>throws the </strong><strong>CancellationException.</strong></p><p>Which means cancellation lands at the <em>next suspension point</em> — not the instant you call cancel():</p><pre>val job = launch { <br>  work() // keeps running even if cancel() was called partway through it <br>  delay(100) // &lt;-- HERE it notices, and throws CancellationException <br>  moreWork() // never runs <br>} <br>job.cancel()</pre><h3>But how does that suspension point know the Job?</h3><p>And this is where it all loops back to the rest of the post. Remember the chain: <strong>the Job lives in the context, and the context rides inside the </strong><strong>Continuation.</strong> When a coroutine suspends through suspendCancellableCoroutine, the CancellableContinuation it gets back registers a cancellation handler on context[Job]. So if the Job is cancelled while the coroutine is parked at that point, the handler fires and resumes the continuation <em>with the exception</em> instead of a value. Job, context, continuation - the exact same three pieces from earlier, now wired up to do cancellation.</p><h3>CPU-bound code never gets the memo</h3><p>The flip side falls right out of this: if your coroutine never hits a suspension point, it never hears about the cancellation.</p><pre>launch { <br>  while (true) { <br>    doLongRunningNonCoOperative() // no suspension -&gt; cancel() is ignored, forever <br>  } <br>}</pre><p>To make a tight loop cancellable, you have to check the flag yourself:</p><ul><li>isActive - while (isActive) { ... }</li><li>ensureActive() - throws CancellationException right away if cancelled</li><li>yield() - an intentional suspension point that gives cancellation its chance to fire</li></ul><h3>Never swallow CancellationException</h3><p>And because the <em>whole mechanism</em> is a thrown CancellationException, catching it and quietly eating it breaks cancellation completely:</p><pre>try { <br>  delay(1000) <br>} catch (e: Exception) { <br>  // oops - this also swallows CancellationException <br>  // the coroutine is &quot;cancelled&quot; but keeps right on running <br> }</pre><p>It’s also why the library treats CancellationException as <strong>normal</strong> rather than a failure: when a child throws it, the parent doesn&#39;t panic - it just reads it as &quot;that child stopped because someone cancelled it.&quot; Any <em>other</em> exception is a genuine failure. CancellationException is simply the sound of cancellation doing its job.</p><h3>Cancelling a scope cancels the whole tree</h3><p>Everything so far has been about cancelling <em>one</em> coroutine. But the reason cancellation matters for <em>structured</em> concurrency is that it propagates — and that’s where the parent/child link from the diagram earlier pays off.</p><p>When you call scope.cancel(), what you&#39;re really cancelling is the scope&#39;s Job — the parent. And that link runs both ways: the child stores a .parent pointer, but the parent also keeps references to all of its children. So a cancelled parent doesn&#39;t just flip its own state — it walks its children and cancels each one, and each of those cancels <em>its</em> children, all the way down to the leaves:</p><p>Take the tree we built earlier — jobwith its two children — and cancel the parent:</p><pre>job.cancel()   // cancels job, and downloadA + downloadB along with it</pre><p>There’s no special “cancel the children” here. Each child is cancelled in exactly the way we just walked through: its state flips to Cancelling, and the next suspension point inside downloadA() / downloadB() throws CancellationException. The parent simply calls cancel() on every child it&#39;s holding.</p><p>The download propagation is what makes a scope <em>safe </em>to throw away. Cancel the scope and nothing it launched keeps running — a viewModelScope torn down when a screen closes, a request scope cancelled when the client disconnects: one cancel() at the root, and the entire subtree underneath it unwinds with no orphans left behind.</p><h3>Putting it all together</h3><p>Let’s trace a single launch from the top and watch the pieces line up:</p><ol><li>You have a <strong>scope</strong> → it holds a <strong>context</strong>.</li><li>The context is a <strong>map of key→value elements</strong>; one of those elements is a Job.</li><li>launch puts a fresh <strong>Job</strong> into the context and runs your block with it.</li><li>Inside the block, every <strong>suspend function</strong> receives that context for free via its hidden <strong>Continuation</strong> - so dispatcher, name, and Job all flow down automatically.</li><li>Call cancel()— on the coroutine or the whole scope — and you flip that Job’s state; the next <strong>suspension point</strong> throws CancellationException, and because a parent cancels its children, the entire subtree unwinds.</li></ol><p>So a lot of what feels like coroutine “magic” isn’t magic at all. It’s three pieces working together: a context that flows through continuations, carrying a Job, whose state a suspension point checks at exactly the right moment. Cancellation, dispatching, naming — all of it rides on that same plumbing.</p><p><em>Next post: </em><strong><em>how we achieve it</em></strong><em> — using these pieces deliberately (</em><em>coroutineScope, </em><em>supervisorScope, scope ownership) to write code that can&#39;t leak.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0262c20d4315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using aar in android library.]]></title>
            <link>https://medium.com/@dikenmaharjan10/using-aar-in-android-library-a6bab1f36934?source=rss-51077e499cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6bab1f36934</guid>
            <category><![CDATA[maven-plugin]]></category>
            <category><![CDATA[gradle-dependencies]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dikenmaharjan]]></dc:creator>
            <pubDate>Thu, 29 May 2025 13:25:26 GMT</pubDate>
            <atom:updated>2025-05-29T13:34:20.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using aar in an android library.</h3><p>When working on an Android project, you might want to include an .aar (Android Archive) file into your module. Adding an .aar to an <strong>Android app module</strong> is straightforward. However, when trying the same in an <strong>Android library module</strong>, you’ll encounter issues because the resulting .aar from the library won&#39;t package the embedded .aar correctly. Let’s explore how to handle this properly.</p><p>I have an aar called “my-aar-library.aar”, which I want to use in my android library.</p><h4>Adding a .aar to an Android App Module</h4><ol><li>Create a folder (e.g., lib) in your app module and place your my-aar-library.aar inside.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*di7tfJc8lerGvkgPXDdo4A.png" /></figure><p>2. Update your app module’s<strong> </strong><strong>build.gradle.kts</strong></p><pre>dependencies {<br>    implementation(files(&quot;$projectDir/lib/my-aar-library.aar&quot;))<br>}</pre><p>Sync Gradle and you’re ready to use the classes in the .aar.</p><p><strong>Hurrah, it’s so simple.</strong></p><h4>Attempting the Same for an Android Library Module</h4><ol><li>Add aar in the library module.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*KUkhEueDmXLGkve4l3rsHA.png" /></figure><p>2. Add the path to the aar in the dependency block in the build.gradle.kts of the consuming module.</p><pre>dependencies {<br>    implementation(files(&quot;$projectDir/lib/my-aar-library.aar&quot;))<br>}</pre><p>3. Sync and build the gradle project.</p><p>Alas!! We get the following error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCmN9z1drEUwGYkQlQ5K1g.png" /></figure><p><strong>Whats happening?</strong></p><p>As the error suggests, we cannot directly add aar to library modules because the resulting aar of the library would not be packaged properly.</p><p>So, what to do.</p><h4><strong>The Correct Solution: Use the Maven Publish Plugin</strong></h4><p>Instead of directly adding the .aar, we need to <strong>publish it to a Maven repository</strong> (local or remote) and then consume it from there.</p><ol><li>In a separate <strong>publishing module</strong> or your <strong>root project’s </strong><strong>build.gradle.kts</strong>, add:</li></ol><pre>plugins {<br>    `maven-publish`<br>}<br><br>publishing {<br>    publications {<br>        create&lt;MavenPublication&gt;(&quot;maven&quot;) {<br><br>            groupId = &quot;com.my-aar&quot;<br>            artifactId = &quot;library&quot;<br>            version = &quot;1.0&quot;<br><br>            artifact(file(&quot;$projectDir/app/lib/my-aar-library.aar&quot;))<br>        }<br><br>        repositories {<br>            maven {<br>                url = uri(file(&quot;$rootDir/repo&quot;))<br>            }<br>        }<br>    }<br>}</pre><p>The <strong>groupId</strong>, <strong>artifactId</strong> and <strong>version</strong> can be anything you want. Just keep it sensible and simple. We will be using the “groupId:artifactId:version” format to include the aar into our library.</p><p>The <strong>artifact</strong>() function takes in the file that we want to publish. In our case, its the aar file that we want to use in our library.</p><p>The <strong>repositories </strong>block can be used to configure where to publish our aar. In our case, we are gonna publish it to <strong>repo</strong> directory of our project directory.</p><p>2. From your terminal, run the following command.</p><pre>./gradlew publish</pre><p>This publishes your .aar along with metadata (POM, checksums) into $rootDir/repo.</p><p>3. You will have the following files in the repo folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*xBvebtHvAxGducfEBtnFkw.png" /></figure><p><strong>4. </strong>Configure the Local Maven Repository</p><p>In your settings.gradle.kts, set your folder to be a maven repository.</p><pre>dependencyResolutionManagement {<br>    repositories {<br>        maven {<br>            // The path where you published the aar.<br>            url = uri(&quot;$rootDir/repo&quot;)<br>        }<br>        // Add other repositories like Google or Maven Central<br>    }<br>}</pre><p>Now, Gradle knows to look in your local repo folder for dependencies.</p><p>5. In the build.gradle.kts of your <strong>consuming library module</strong>:</p><pre>dependencies {<br>    implementation(&quot;com.my-aar:library:1.0&quot;)<br>}</pre><p>The com.my-aar:library:1.0 is my maven coordinates or maven GAV for my published artifact. It’s the same that you used to configure maven-publish when publishing the aar. The maven coordinates is of the formgroupId:artifactId:version</p><p>4. Voila, we’ve published the AAR to a local directory, set it up as a Maven repository, and integrated the artifacts into our library.</p><h4><strong>Some Caveats</strong></h4><ul><li>You can configure <strong>Maven publishing</strong> either in your <strong>root project’s </strong><strong>build.gradle.kts</strong> or, for a cleaner separation of concerns, you can set up a <strong>dedicated module solely for publishing the </strong><strong>.aar</strong>. This way, your library’s build logic stays clean and you can manage publishing independently.</li><li>If you plan to distribute your library, publish the .aar to a <strong>remote Maven repository</strong> (e.g., GitHub Packages, Artifactory, Maven Central).</li><li>If your .aar depends on other libraries, you’ll need to ensure the <strong>generated POM</strong> reflects those dependencies, or else consumers might face missing dependencies.</li></ul><h4>Maven Repository Options</h4><p>When ready to publish remotely, consider:</p><ul><li>Maven Central (Sonatype OSSRH): Free for open-source, widely used.</li><li>GitHub Packages: Easy to set up if your project is on GitHub.</li><li>JFrog Artifactory / GitLab Packages: Great for enterprise and private projects.</li></ul><h4>Why Maven?</h4><p>Library modules produce their own .aar artifacts, and Gradle doesn’t support merging prebuilt .aar files into these outputs. Maven publishing solves this by treating your .aar as a proper dependency with metadata.</p><h4>Summary</h4><p>Adding an .aar to an app module works with files(…), but adding an .aar to a library module requires publishing to a Maven repository (local or remote). By using Maven Publish Plugin, we:</p><ul><li>Publish the .aar to a local Maven repository.</li><li>Configure the project to resolve dependencies from that repository.</li><li>Reference the artifact with its GAV coordinates groupId:artifactId:version.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6bab1f36934" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>