<?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 Andrei Riik on Medium]]></title>
        <description><![CDATA[Stories by Andrei Riik on Medium]]></description>
        <link>https://medium.com/@andrei_r?source=rss-ff1606e3bbf7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sxDr_A_NnLzUS6RlkbnjSg.jpeg</url>
            <title>Stories by Andrei Riik on Medium</title>
            <link>https://medium.com/@andrei_r?source=rss-ff1606e3bbf7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 06:34:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrei_r/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[Will IDEs Survive the Era of Agentic Development?]]></title>
            <link>https://medium.com/mobilepeople/will-ides-survive-the-era-of-agentic-development-6f1bcdab6b3c?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f1bcdab6b3c</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 08:36:01 GMT</pubDate>
            <atom:updated>2026-11-09T08:36:01.433Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI agents write more and more of our code. Do we still need the tools we used to write the code with?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENwrKZG5b_x8gMBN8ylmAA.jpeg" /></figure><p>I’ve been writing mobile apps for 13 years, and for most of that time Android Studio or Visual Studio Code was open from morning till evening. I typed code there, jumped between files, renamed things and set breakpoints. Then at some point this year I noticed I’d spent a whole afternoon without typing a single line of Kotlin. Claude Code wrote it. I read it.</p><p>So I started asking myself an awkward question: if I’m not the one writing the code, why do I keep a tool built for writing code?</p><p>My short answer: IDEs will survive, but not as the place where you write code. They’re becoming the place where code is understood and verified. And whether you need it at all depends on how you work with AI.</p><h3>Two ways to build with AI</h3><p>I see two main ways people work with agents. Most of us switch between them, sometimes several times a day. I certainly do.</p><p><strong>Mode 1: Vibe coding</strong></p><p>You describe what you want, the agent writes it, you run it, and if it works, you move on. You rarely read the diff.</p><p>It’s fast. A prototype, an internal tool, a weekend game or a throwaway script takes an hour instead of a week, and you can start with almost no setup.</p><p>The price is that you understand less of the codebase with every prompt. After a while the code belongs to the agent more than to you. Worse, you don’t notice when things go wrong. Each step looked fine. Together they were a mess.</p><p>Do you need an IDE for this? Mostly not. An agent in a terminal or a desktop app (Claude, Codex, Antigravity), a phone or browser to check the result, and maybe a simple editor for a quick fix are enough. If you never read the code, a powerful tool for reading code is overkill.</p><p><strong>Mode 2: You own the codebase</strong></p><p>Here the agent is a fast pair programmer, but you’re in charge. You set the architecture and the rules, review every meaningful change, and pull the agent back when it drifts.</p><p>You keep the mental model of the system. Quality and security stay under your control, and a year later the code is still maintainable, whether by you, your team or the next agent.</p><p>But it’s slower. Reviewing is real work, and it eats a big part of the gain. <a href="https://pipedot.org/article/6YN1P">A METR study from 2025</a> found that experienced open-source developers working in their own large repositories were about 19% slower with AI tools, while they believed they were about 20% faster. A lot of the lost time went into reviewing and fixing suggestions that were close to right but not quite. Models have improved a lot since then. Review is still the bottleneck, though.</p><p>This is where the IDE earns its place, maybe even more than before.</p><p>A diff alone doesn’t tell you enough. To own the code, you must understand it. To judge a change, you need context: who calls this function, what implements this interface, where else this pattern appears. “Find usages”, call hierarchy, and easy navigation answer that in seconds. A plain diff viewer doesn’t.</p><p>Small fixes are faster by hand. Renaming a variable or flipping one condition takes me 10 seconds. Writing a prompt and waiting for the agent takes longer, and sometimes it “fixes” three other things along the way (this may be improved with good AI rules though).</p><p>Then there’s platform tooling. I can’t imagine replacing the Layout Inspector, the profiler, the emulator or Compose previews with a chat window. Other platforms have their own versions of these tools, and they all live in the IDE.</p><p>In this mode, the IDE stops being a typewriter, it becomes something like a <strong>microscope</strong>.</p><h3>How IDEs are adapting</h3><p>IDE vendors understand this shift well, and the last year shows three clear directions.</p><p><strong>1. The IDE becomes a host for any agent.</strong> Instead of betting on one built-in assistant, IDEs open up. <a href="https://zed.dev/blog/jetbrains-on-acp">JetBrains and Zed co-sponsor the Agent Client Protocol (ACP)</a>, a vendor-neutral standard for connecting agents to editors. JetBrains AI now lets you use Claude Agent, Codex, Gemini, and its own agent Junie under one subscription. The message is simple: “bring your favorite agent, but use it inside our tools”.</p><p><strong>2. IDE intelligence becomes a tool for agents.</strong> This is the most interesting change. Agents usually explore code with grep and file reads. But IDEs have spent decades building precise semantic indexes. In 2026, <a href="https://blog.jetbrains.com/ai/2026/05/what-happens-when-you-give-agents-ide-native-seach-tools/">JetBrains gave</a> Junie and the Codex agent direct access to its static-analysis search symbol search, call hierarchy, and usage search instead of grepping raw text. The IDE’s “brain” becomes an API for the agent. What does this unlock? Reduced token spending and switching to cheaper agents without quality loss.</p><p><strong>3. New environments for orchestrating agents.</strong> In March 2026, <a href="https://www.techzine.eu/news/devops/139409/jetbrains-air-agentic-development-environment-in-preview/">JetBrains previewed <strong>Air</strong></a>, an “agentic development environment” built on the abandoned Fleet platform. It runs several agents in parallel on different tasks, in a local workspace, a Git worktree or Docker, and is designed around delegating work and reviewing results. Cursor, VS Code with Copilot, and others move in the same direction: more focus on task lists and agent sessions.</p><p>So the IDE is not dying, it is splitting into two layers: a <strong>control panel</strong> where you supervise agents, and a <strong>deep inspection tool</strong> for when you need to understand the code yourself.</p><h3>Follow the money: JetBrains</h3><p>JetBrains is a good company to watch here. It has lived off selling IDEs for 25 years without venture funding, so its numbers say a lot about the IDE business itself.</p><p>And the numbers are mixed.</p><p>According to the statutory (unconsolidated) filing of its main Czech entity, JetBrains s.r.o. had record revenue of about CZK 16 billion (~$710M) in 2025, but growth slowed to around 6.3%, the lowest in five years. The entity posted a <a href="https://braindetox.kr/en/posts/jetbrains_2025_net_loss_czech_filing_2026.html">net loss of about CZK 315 million</a>, the first in its tracked history.</p><p>At the same time, JetBrains’ own <a href="https://www.jetbrains.com/lp/annualreport-2026/">Annual Highlights</a> report 25.69% year-over-year revenue growth (a different, company-wide scope) and 240% growth in paid AI users from Q4 2024 to Q4 2025.</p><p>Now compare that with Cursor. Its annualized revenue went from about <a href="https://www.secondtalent.com/resources/cursor-statistics/">$100M in January 2025 to more than $4B by June 2026</a>.</p><p>I don’t think the IDE business is collapsing. People still pay for professional tools. But the growth has moved to AI-first products, and pricing is shifting from “per seat” to “per AI credit”. IDE companies now have to spend a lot just to stay in the race, and I’d say JetBrains joined that race a bit late.</p><p>One more data point: in the Stack Overflow 2026 Developer Survey, <a href="https://visualstudiomagazine.com/articles/2026/10/06/stack-overflow-2026-survey-vs-code-leads-visual-studio-takes-third.aspx">VS Code is still the most used development environment</a>, while Claude Code, a terminal-first agent, is the most used coding agent among respondents. Developers didn’t drop their editors. They added an agent next to them. That’s exactly my setup: Claude Code in one window, Android Studio in the other.</p><h3>The junior problem</h3><p>One thing worries me. Seniors can review AI code because they spent years writing code by hand. I learned what a bad abstraction looks like by writing quite a few of them. How will juniors build that intuition if all they ever do is read agent output? Maybe the IDE will end up being as much a learning tool as a work tool.</p><h3>Conclusion</h3><p>If you only vibe code, you can live without an IDE today. But if you’re responsible for a codebase that has to keep working next year, you need something that helps you understand and check code faster than an agent can produce it.</p><p>So no, I’m not deleting Android Studio and Visual Studio Code. I just use them differently. I use it to check what the agent wrote before I trust it.</p><p>​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f1bcdab6b3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/will-ides-survive-the-era-of-agentic-development-6f1bcdab6b3c">Will IDEs Survive the Era of Agentic Development?</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Carousel Pager Using Jetpack Compose]]></title>
            <link>https://medium.com/mobilepeople/writing-carousel-pager-using-jetpack-compose-8b30eb87dd7b?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b30eb87dd7b</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 15:22:33 GMT</pubDate>
            <atom:updated>2025-03-11T15:22:33.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was migrating a carousel pager from RecyclerView with custom <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.LayoutManager">LayoutManager </a>to Jetpack Compose, and I was pleasantly surprised at how easy it was to achieve with <a href="https://developer.android.com/develop/ui/compose/layouts/pager">HorizontalPager</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poe4TiuZPkLoFjf0p8BBcA.png" /></figure><p>This is how it should look in the end:</p><figure><img alt="Expected result" src="https://cdn-images-1.medium.com/max/216/1*G40q_gHR6BLBS4YMHd75sg.gif" /><figcaption>Expected result</figcaption></figure><p>A few properties need to be implemented:</p><ul><li>Scale pages according to the scroll position</li><li>Pages may overlap</li><li>The central page must always be above the others</li><li>Smooth scrolling experience</li></ul><h3>Step by step implementation</h3><p>How to achieve this? The documentation gives us a <a href="https://developer.android.com/develop/ui/compose/layouts/pager#scroll-effects">clue</a> about the scrolling offset fraction that we can observe.</p><blockquote>Note: The most convenient and performant way to apply basic visual transformations is to use the <a href="https://developer.android.com/develop/ui/compose/graphics/draw/modifiers#graphicsLayer">graphicsLayer</a> function. We’ll use it later, but first, we need to calculate the necessary values, such as scale and translation.</blockquote><p>If we can observe the fraction, we can apply transformations to our Composables based on it. The fraction is given in the <strong>-0.5..0.5</strong> range via the <strong>pagerState.currentPageOffsetFraction</strong> property, so let’s transform it to the <strong>0..1</strong> range for future convenience:</p><pre>val fractionAbs = (pagerState.currentPageOffsetFraction * 2f)<br>    .coerceIn(-1f, 1f)<br>    .absoluteValue</pre><p>Now, let’s transform the fraction into a final scale. Here is one of the possible ways. If the page is current, then scale it from <strong>x0.8</strong> at the edge of the flipping up to <strong>x1</strong> in the center:</p><pre>val scale = if (currentPage == index) {<br>    (1f - fractionAbs * 0.2f)<br>} else {<br>    // Must not be more than the minimum above<br>    // E.g. (0.7 + 0.1) == (1 - 0.2) at the moment<br>    0.7f + fractionAbs * 0.1f<br>}.coerceIn(0f, 1f)</pre><p>Now we have scaling, but we need to compensate the space for the decrease in scale on the left and right pages. Let’s do it with the <strong>translationX</strong> property, here is an example value calculation:</p><pre>val txBase: Dp = 96.dp<br><br>val txPx = (with(this) { txBase.toPx() }) * (1f - fractionAbs)<br><br>translationX = TODO()</pre><p>Lastly, we need to position the center page, so that it always overlaps left and right pages. A simple and straightforward way to do this is to utilise the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).zIndex(kotlin.Float)">.zIndex</a> function which controls the drawing order:</p><pre>.zIndex(<br>    if (pagerState.currentPage == index) 1f else 0f<br>)</pre><p>Now it’s time to assemble all together into a reusable Composable. Here is one of the possible implementations:</p><pre>@Immutable<br>data class CarouselPagerData&lt;T&gt;(<br>    val items: List&lt;T&gt;,<br>)<br><br>@Composable<br>fun &lt;T&gt; CarouselPager(<br>    modifier: Modifier,<br>    data: State&lt;CarouselPagerData&lt;T&gt;&gt;,<br>    contentPadding: PaddingValues = PaddingValues(32.dp),<br>    txBase: Dp = 96.dp,<br>    content: @Composable BoxScope.(T) -&gt; Unit,<br>) {<br>    val pagerState = rememberPagerState { data.value.items.size }<br>    HorizontalPager(<br>        modifier = modifier,<br>        state = pagerState,<br>        contentPadding = contentPadding,<br>    ) { index -&gt;<br>        val item = data.value.items[index]<br>        Box(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .zIndex(<br>                    if (pagerState.currentPage == index) 1f else 0f<br>                )<br>                .graphicsLayer {<br>                    val currentPage = pagerState.currentPage<br>                    // x2 because it is -0.5 ... 0.5 -&gt; -1 ... 1<br>                    val fractionAbs = (pagerState.currentPageOffsetFraction * 2f)<br>                        .coerceIn(-1f, 1f)<br>                        .absoluteValue<br>                    val scale = if (currentPage == index) {<br>                        (1f - fractionAbs * 0.2f)<br>                    } else {<br>                        // Must not be more than the minimum above<br>                        // E.g. (0.7 + 0.1) == (1 - 0.2) at the moment<br>                        0.7f + fractionAbs * 0.1f<br>                    }.coerceIn(0f, 1f)<br>                    scaleX = scale<br>                    scaleY = scale<br>                    val txPx = (with(this) { txBase.toPx() }) * (1f - fractionAbs)<br>                    translationX = if (index &gt; currentPage) {<br>                        -txPx<br>                    } else if (index &lt; currentPage) {<br>                        txPx<br>                    }<br>                },<br>        ) {<br>            content(item)<br>        }<br>    }<br>}</pre><p>That’s it, works like a charm!</p><h3>Bonus</h3><p>You can always play with the parameters. For example, to achieve flat scaling of secondary pages and gradual scaling of only the central page, you can use the following parameters:</p><pre>val scale = if (currentPage == index) {<br>    (1f - fractionAbs * 0.3f)<br>} else {<br>    0.7f<br>}.coerceIn(0f, 1f)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*l_Qcb8-8DOzsDfn8o241Lg.gif" /><figcaption>Gradual scaling of the central page only</figcaption></figure><h3>Conclusion</h3><p>Creating a carousel pager with <strong>HorizontalPager</strong> is much easier than doing it with <strong>RecyclerView</strong>. Thanks to those engineers who provided convenient observable properties that are easy to use.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b30eb87dd7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/writing-carousel-pager-using-jetpack-compose-8b30eb87dd7b">Writing Carousel Pager Using Jetpack Compose</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tip for testing Kotlin Coroutines with Dispatchers]]></title>
            <link>https://medium.com/mobilepeople/tip-for-testing-kotlin-coroutines-with-dispatchers-c208c844226b?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c208c844226b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 07:17:08 GMT</pubDate>
            <atom:updated>2024-09-06T07:17:08.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybTfu3cDrj8WitVYLxTKwA.jpeg" /></figure><p>In modern Kotlin development, one of the popular approaches to testing coroutines <a href="https://developer.android.com/kotlin/coroutines/test?authuser=1#injecting-test-dispatchers">is to pass a custom dispatcher</a> to the class or function under the test.</p><p>In your class:</p><pre>class Repository(<br>    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO<br>) ...</pre><p>In your test:</p><pre>@Test<br>fun someTest() = runTest {<br>    val dispatcher = StandardTestDispatcher(...)<br>    val repository = Repository(dispatcher)<br>    ...</pre><p>But I always missed the way it was done in RxJava.</p><p>For example, we can do it in a few lines with <strong>no additional changes</strong> in the code that is tested:</p><pre>RxJavaPlugins.setIoSchedulerHandler { <br>    Schedulers.trampoline() <br>}</pre><h3>Can we achieve the same simplicity with Coroutines? Can we not worry about passing the dispatcher as a parameter?</h3><p>Well, <a href="https://developer.android.com/kotlin/coroutines/test?authuser=1#setting-main-dispatcher">there is a way for the main dispatcher</a>:</p><pre>@Test<br>fun settingMainDispatcher() = runTest {<br>    val dispatcher = UnconfinedTestDispatcher(...)<br>    Dispatchers.setMain(dispatcher)<br>    ...</pre><p>Unfortunately, there is no way to do the same for other types of dispatchers such as <strong>Dispatchers.IO</strong> and <strong>Dispatchers.Default</strong>.</p><p>The good news is that we can do it ourselves. Here is an example:</p><pre>import kotlinx.coroutines.CoroutineDispatcher<br>import kotlinx.coroutines.Dispatchers<br>import org.jetbrains.annotations.VisibleForTesting<br><br>/**<br> * Dispatchers that can be easily changed for testing.<br> * It&#39;s similar to &quot;RxJavaPlugins.set...&quot;<br> */<br>object DispatchersHub {<br><br>    var Main: CoroutineDispatcher = Dispatchers.Main<br>        private set<br><br>    var Default = Dispatchers.Default<br>        private set<br><br>    var IO = Dispatchers.IO<br>        private set<br><br>    var Unconfined = Dispatchers.Unconfined<br>        private set<br><br>    @VisibleForTesting<br>    fun set(<br>        main: CoroutineDispatcher = Main,<br>        default: CoroutineDispatcher = Default,<br>        io: CoroutineDispatcher = IO,<br>        unconfined: CoroutineDispatcher = Unconfined,<br>    ) {<br>        Main = main<br>        Default = default<br>        IO = io<br>        Unconfined = unconfined<br>    }<br><br>    @VisibleForTesting<br>    fun reset() {<br>        Main = Dispatchers.Main<br>        Default = Dispatchers.Default<br>        IO = Dispatchers.IO<br>        Unconfined = Dispatchers.Unconfined<br>    }<br>}</pre><p>Usage example:</p><pre>// Code before<br>someFlow.flowOn(Dispatchers.IO)<br><br>// Code after<br>someFlow.flowOn(DispatchersHub.IO)</pre><p>As you can see, no additional parameters must be passed as arguments. At the same time, you can change the dispatcher dynamically for testing.</p><p>In tests (you can do it even simpler via test rules):</p><pre>@Before<br>fun setUp() {<br>    DispatchersHub.set(<br>        io = UnconfinedTestDispatcher()<br>    )<br>}<br><br>@After<br>fun tearDown() {<br>    DispatchersHub.reset()<br>}</pre><p>That’s it. You can write your main code as usual.</p><h3>Bonus point.</h3><p>You can write handy extensions and not worry about passing test dispatchers.</p><p>An example:</p><pre>fun &lt;T&gt; Flow&lt;T&gt;.fromIo() =<br>    flowOn(DispatchersHub.IO)</pre><p>Thanks for reading! Feel free to share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c208c844226b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/tip-for-testing-kotlin-coroutines-with-dispatchers-c208c844226b">Tip for testing Kotlin Coroutines with Dispatchers</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating UI-oriented Android library to Compose Multiplatform (Android/iOS)]]></title>
            <link>https://proandroiddev.com/migrating-ui-oriented-android-library-to-compose-multiplatform-android-ios-862129f498a9?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/862129f498a9</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Mon, 20 May 2024 15:28:03 GMT</pubDate>
            <atom:updated>2024-05-20T15:28:03.699Z</atom:updated>
            <content:encoded><![CDATA[<p>After years of evolution, it seems like we can finally say that Kotlin Multiplatform is here to stay. However, I still had this awkward feeling that it’s not really as convenient and competitive to share only business logic across platforms, especially whereas React Native, Flutter, and other technologies can do more. That’s why I was really excited to see the first alpha version of the highly anticipated Compose Multiplatform for iOS last year.</p><p>The puzzle has finally come together. Now Android developers can create iOS apps in Kotlin with minimal additional effort. But is this really the case? Let’s find out. Here, I will describe a library migration. When migrating an entire application, some points may differ.</p><blockquote>Note: <br>This happened in Spring 2024 with Kotlin 1.9.22. <br>With Kotlin 2.x and other recent advancements, some things may be different.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzhGXhFcb13BT40Lh0kepA.png" /></figure><h4>About my case</h4><p>We have Android/Kotlin and iOS/Swift clients. Both clients use a self-made library with the following UI features:</p><ul><li>Static loadable pictures</li><li>Loadable GIFs</li><li>Videos (streaming loading from the CDN)</li><li>All this is placed in vertical lists with horizontal lists inside</li></ul><p>Atop of this:</p><ul><li>Networks communications</li><li>Disk caching</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*4Eb5MmEXdZwZC8WkYBB6yA.gif" /><figcaption>What our library looks like with Compose Multiplatform</figcaption></figure><p>For us it was a good starting point to test the Compose Multiplatform capabilities and performance. If anything could go wrong — it will be here.</p><h4>Why Compose Multiplatform?</h4><p>Some sources describe Jetpack Compose as a declarative API. To me, the main advantage of Jetpack Compose compared to traditional XML layouts is the flexibility. And when you have your layouts in Jetpack Compose, then the migration to Compose Multiplatform is not really hard.</p><p>From the business perspective it’s easier to unify the codebase step by step without major disturbance and the need for additional developers. That is what Compose Multiplatform allows you to do.</p><p>A quick reminder how it works, according to <a href="https://blog.jetbrains.com/kotlin/2023/05/compose-multiplatform-for-ios-is-in-alpha/">Jetbrains</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e8nSyumtbep-jujf.png" /><figcaption><em>Compose Multiplatform is an optional layer for Kotlin Multiplatform applications that allows you to build declarative user interfaces once and use them for multiple target platforms.</em></figcaption></figure><h4>Obstacles in codebase</h4><p>Sometimes we all write or use non-KMP code. Sometimes a lot. <br>There are typical examples:</p><ul><li>Java code</li><li>Incompatible libraries as dependencies (Dagger 2, RxJava, Retrofit and others)</li><li>XML layouts, Views, Fragments</li><li>Android Services, Push notifications, In-app purchases</li><li>and more…</li></ul><p>Here we have 2 main possible solutions:</p><ol><li>Rewrite the code / migrate to KMP-compatible library and put it into the <strong>commonMain </strong>folder.</li><li>Put the incompatible code into platform-specific submodules: <strong>androidMain</strong> and <strong>iosMain</strong>.</li></ol><p>In fact you can always put some code into platform-specific submodules but in this case you have to write it for iOS or implement it on iOS as well.</p><h4>How to write iOS-specific code?</h4><p>There are 2 main options to define or use the iOS platform-specific code:</p><p><strong>Option 1. </strong><br><a href="https://kotlinlang.org/docs/multiplatform-expect-actual.html">Expect/actual</a> functions with the implementation in <strong>iosMain</strong> folder.<br>Here is how the structure looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*DH_FZujZ3kBdwdU1qWEP3w.png" /></figure><p><strong>Option 2. </strong><br>Provide some connectors that you can invoke from iOS side.<br>Here is an example. In <strong>commonMain </strong>we define an empty logger:</p><pre>object Bridge {<br>    var logger: (String) -&gt; Unit = {}<br>    ...<br>}</pre><p>In iOS/Swift app we assign an implementation for the logger:</p><pre>import ...<br><br>Bridge.shared.logger = {<br>    print(&quot;ios log: &quot; + $0)<br>}</pre><p>It’s just a simple case. In fact, we can connect almost everything this way. It’s even possible to define an interface in <strong>commonMain</strong> and write the whole implementation in Swift independently.</p><p>Of course, the more platform-specific code you need to write, the worse it is. In my situation, we have about <strong>9%</strong> of the entire library’s codebase in iosMain and <strong>13%</strong> in androidMain. This percentage might be lower in your case.</p><h4>How to start migrating?</h4><p>So we have Android/Kotlin and iOS/Swift clients. How to start the unification?</p><p>In case of Android, it’s possible to rewrite and integrate KMP-compatible code into existing app or library step-by-step. The language remains the same, but the approaches and libraries that you depend on may be changed.</p><p>In a simple case it will be like:</p><ol><li>Create a KMP module in your codebase.</li><li>Move your code iteratively to <strong>commonMain</strong>.</li><li>Make connectors for parts that can’t be moved away from the platform.</li></ol><p>In my case, we decided to start by migrating our self-made UI-focused library that both iOS and Android clients depend on. We had to rewrite the library completely because it was deeply based on RxJava and Fragments with XML layouts.</p><h4>Our major technology shifts</h4><p><strong>RxJava → Coroutines / Flow </strong><br>If you use Rx, you need to migrate to Flow or use some KMP alternatives like <a href="https://github.com/badoo/Reaktive">Reaktive</a>.</p><p><strong>Retrofit → Ktor </strong><br>Ktor is a quite convenient network library. There were no major troubles with it. You just have to google a few times how to write what you were used to and that’s it.</p><p><strong>Room → Room?</strong><br>In my case the plain disk caching with <strong>Okio</strong> was an acceptable substitution. But in fact <a href="https://developer.android.com/kotlin/multiplatform/room">Room supports KMP</a> as well.</p><p><strong>Glide → Coil 3 + Self-made GIF implementation for iOS.</strong><br>Coil 3 is still in alpha but it works. The problem in my case was the inability to play GIFs on iOS. Unfortunately it took me several days to figure out the issue and implement the solution with disk caching.</p><blockquote>Caveats:</blockquote><blockquote>- Crash in the Jetbrains’ SVG parser on iOS that affects both Coil3 and Kamel. <br><a href="https://github.com/JetBrains/compose-multiplatform/issues/4676">The ticket</a> is still unresolved.</blockquote><blockquote>- Coil 3 doesn’t support GIFs out of the box yet. You have to write it by yourself. <br>As well as disk cache for it.</blockquote><p>The basic contract for images in my case:</p><pre>@Composable<br>expect fun LoadableImage(<br>    modifier: Modifier,<br>    url: String,<br>    imageColorFilter: ColorFilter? = null,<br>    size: Size? = null,<br>)</pre><p><strong>Jetpack ExoPlayer → ExoPlayer + AVPlayer</strong><br>We use expect/actual to substitute the player for each platform. <br><a href="https://developer.android.com/media/media3/exoplayer">ExoPlayer</a> is a powerful solution for Android with the disk caching and streaming playback capabilities.<br><a href="https://developer.apple.com/documentation/avfoundation/avplayer/">AvPlayer</a> is a default solution on iOS.</p><p>The basic contract of the player:</p><pre>@Composable<br>expect fun VideoPlayer(<br>    modifier: Modifier, <br>    url: String, <br>    volumeEnabled: State&lt;Boolean&gt;,<br>)</pre><h4>How to build for Android</h4><p>In case of Android everything is similar to the ordinal android library. The library can be used as a module in the application. It’s our choice for now.</p><p>Another option is to use Gradle Composite Builds. See this article for details:</p><p><a href="https://medium.com/@andrei_r/gradle-composite-build-instead-of-mono-repository-7a8fce3612ca">Gradle Composite Build instead of mono-repository</a></p><p>Lastly, you can assemble the library to <strong>.aar</strong> file using a Gradle task <strong>bundleReleaseAar</strong>.</p><h4>How to build for iOS</h4><p>During local development we build an XCFramework and put it into the iOS project. The logic is described here:</p><p><a href="https://kotlinlang.org/docs/multiplatform-build-native-binaries.html#build-xcframeworks">Build final native binaries | Kotlin</a></p><p>In short the process is:</p><ol><li>Invoke a gradle task. <br>It may be <strong>iosX64Binaries</strong> or <strong>iosArm64Binaries</strong> for local builds (faster) or <strong>assembleReleaseXCFramework</strong> for final binaries (slower).</li><li>Copy the result from <strong>build/bin/iosArm64/releaseFramework</strong> (or similar path) into the iOS project.</li><li>Wait a bit until it’s synchronised by Xcode.</li><li>Done. Use Kotlin code in your iOS project.</li></ol><p>With the automated CI/CD pipeline the process is a bit different but it’s another story.</p><blockquote>Caveat:<br>The size of the produced library for iOS (XCFramework) is huge: <strong>378 MB</strong> in case of <strong>assembleReleaseXCFramework.</strong></blockquote><h4>Results in my case</h4><p>Although our migration is in the pre-production stage at the moment, some conclusions can already be made.</p><p>🟢 <strong>Functionality.</strong> <br>All major functions of our library were migrated. <br>Functional requirements met with a few non-critical exceptions.</p><p>🟢 <strong>Codebase. </strong><br>Rewriting like this is the opportunity to remove a lot of legacy code. <br>The numbers: <br><strong>Before:</strong> 10k LoC, 1.2k XML lines<br><strong>After:</strong> 4k LoC<br><strong>Result:</strong> x2.5 less code compared to the legacy version.</p><p>🟢 <strong>Performance.</strong><br>On iOS it scrolls smoothly even on iPhone SE. <br>On low-end Android devices it feels not so smooth like it was with the XML version, but it’s not critical.</p><p>🟡 <strong>Developer productivity.</strong><br>In general, if you are familiar with modern Android development and Jetpack Compose, there will be no major issues for you. With one exception in my experience: there is no Preview in Android Studio and IDEA. <a href="https://blog.jetbrains.com/kotlin/2024/02/compose-multiplatform-1-6-0-release/#preview-annotation-for-fleet">It works for Fleet</a>, but in AS/IDEA you write Composable functions blindly.</p><p>🟡 <strong>Binary size.</strong><br>Android APK: + 0.5 MB<br>iOS IPA: + 18 MB</p><p>🟡 <strong>Library size.</strong><br>Huge XCFrameworks size. More than 300 MB.</p><p>🔴 <strong>Build time.</strong><br>Long build time for iOS. It depends on the machine but we see numbers like 17 minutes for the library with only 4k LoC.</p><h4>Conclusion</h4><p>It’s absolutely possible to write a cross-platform UI in Kotlin in 2024.</p><p>The great thing about KMP and Compose Multiplatform is that if you have to write code in Kotlin anyway, why not write it in a KMP-compatible way?</p><p>The result is acceptable in our case, which can be considered as a stress test. Also, we need to keep in mind that Compose Multiplatform for iOS is in the alpha stage and Kotlin 2 is ahead.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862129f498a9" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/migrating-ui-oriented-android-library-to-compose-multiplatform-android-ios-862129f498a9">Migrating UI-oriented Android library to Compose Multiplatform (Android/iOS)</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[Kotlin, Java, and C#. Differences and Similarities.]]></title>
            <link>https://medium.com/mobilepeople/kotlin-java-and-c-differences-and-similarities-f11b6e2f1287?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11b6e2f1287</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 07:31:39 GMT</pubDate>
            <atom:updated>2024-02-29T07:31:39.602Z</atom:updated>
            <content:encoded><![CDATA[<p>You may know that Java and Kotlin programming languages are similar. But what might be surprising is that C# is not that far off. Let’s do some overview.</p><p>Here, I will first cover a few fundamental features and then go over some syntax details that are worth mentioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrOxPJmKs24uD-LFcVPU9A.png" /></figure><h4>Age and popularity</h4><p>Java appeared in 1995, and C# in 2000. Kotlin first appeared much later, in 2011, and the first stable version was released in 2016.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aZKCzQ9Jrz4E988oapg54w.png" /></figure><p>According to <a href="https://www.tiobe.com/tiobe-index/">some data</a>, Java is the 4th most popular programming language in 2024. C# is right behind it in 5th place. Kotlin is far behind in 17th place.</p><p>Here is a more visual picture according to <a href="https://www.statista.com/statistics/793628/worldwide-developer-survey-most-used-languages/">another source (statista.com)</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*bjBlmpjYdMvOXus922paeg.png" /></figure><h4>“Write once, run anywhere”</h4><p>The main slogan behind Java. This is a good example that in 1995 people were already thinking about cross-platform development, as we do nowadays. C# and Kotlin also try to follow this principle in their own way.</p><p>Java uses a virtual machine to run code in different environments. C# can use the .Net framework for the same purpose. Kotlin can be compiled into a JVM and run wherever Java can, or it can be compiled for different platforms independently.</p><h4>Platforms and applicability</h4><p>Java is supported on a wide range of platforms, including Windows, macOS, and Linux. Nowadays the largest applicability of Java is server-side development.</p><p>C# is primarily used on Windows, although it can be used on other platforms with the .NET Core runtime. C# is used for server-side but also can be helpful for frontend development with <a href="https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor">Blazor</a>. Atop of this C# is used in Unity cross-platform game engine and Xamarin cross-platform framework.</p><p><a href="https://www.jetbrains.com/kotlin-multiplatform/">Kotlin Multiplatform</a> can be compiled for Android, iOS, Web, and Desktop. Kotlin can be used for server-side development almost anywhere Java is used. Also, it’s the main programming language for Android development. Additionally, with the latest updates of the Compose Multiplatform framework, Kotlin is a promising language for cross-platform mobile development.</p><h4>Bytecode / Intermediate language</h4><p>All 3 languages are compiled. They compile source code to an intermediate format before translating it to machine code. Java is compiled to <a href="https://en.wikipedia.org/wiki/Java_bytecode">bytecode</a>. Kotlin can be compiled to bytecode as well if it targets JVM platform. C# compiles to something similar to bytecode, it’s called <a href="https://learn.microsoft.com/en-us/dotnet/standard/managed-code#intermediate-language--execution">Intermediate Language by Microsoft</a>.</p><h4>Garbage collectors</h4><p>Another similarity between these languages is that they all have automatic memory management (garbage collectors). The general rule for releasing the memory is simple: if an object is not referenced by someone, it should be cleaned from memory.</p><p>Of course, you have to watch your references to prevent memory leaks but in general, Garbage Collector saves a lot of time for programmers.</p><blockquote>For comparison: the most famous language where you have to manage memory yourself with functions like malloc and free is C.</blockquote><h4>Object-oriented</h4><p>All these languages are object-oriented which means they support the main concepts of the OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.</p><blockquote>Fun fact: originally, C# was called “Cool” or “C-like Object Oriented Language”.</blockquote><h4>Strong types</h4><p>Kotlin, Java, and C# have strong typing systems. This means that the type of a variable is checked before the program is run, and any type mismatches are flagged as errors. This is in contrast to weak typing, where type-checking is done at runtime. In general, it helps to prevent bugs and makes the code more reliable.</p><blockquote>For comparison: the most popular language without strong typing is JavaScript. Weak typing may be convenient for small applications, but for a larger codebase it’s a common source of errors.</blockquote><h4>Structures, inline value classes</h4><p>What is structure (struct)? It’s a set of fields, like a lightweight class, that doesn’t require heavy class allocations. Structs are useful when you operate with pure data values.</p><p>In C# structure types are part of the language, whereas in Java and Kotlin it’s not the case.</p><p>In Kotlin, however, there is something similar — inline value classes, but they are very limited in comparison to structs. Why did I mention it as an analog of structures? In some cases, you can pack several values into a single Long or Double variable and it will serve as a struct. For example, take a look at IntOffset class in Jetpack Compose.</p><p>The absence of structs can be mitigated with the Objects Pool pattern which reuses created objects without new allocations, but this requires additional programming efforts.</p><pre>// Kotlin: Value class will be compiled as a primitive<br><br>@JvmInline<br>value class SomeValueClass(<br>    val first: Int<br>)</pre><pre>// C#: Struct example<br><br>public struct SomeStruct <br>{<br>    public int First;<br>    public float Second;<br>}</pre><h4><strong>Null safety</strong></h4><p>Kotlin has built-in null safety features that help prevent null pointer exceptions in compile time. However, it doesn’t mean that we don’t have null-related errors in Kotlin, because we can still use unsafe casts !!.</p><p>In Java, it’s not the core part of the language but you can use static analysis and Nullable annotations. Also, Optional wrappers come to help.</p><p>C# has the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator">null-coalescing</a> operator ?? which helps reduce code boilerplate. Also, it has the option to enable <a href="https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references">compile-time warnings</a> for possible null errors in its latest versions.</p><h4><strong>Exception handling</strong></h4><p>In Java there are checked and unchecked Exceptions. You must declare checked exceptions with the throws keyword and use a try/catch when invoking it.</p><p>In Kotlin you don’t have to declare throws signature and you don’t have to catch Exceptions. It’s optional. The same in C#.</p><p>This may be controversial. Some people like checked exceptions because they declare clearly what to expect from a method. Some people prefer <a href="https://www.artima.com/articles/the-trouble-with-checked-exceptions">simplicity without checked exceptions</a>.</p><h4>Pointers / ref</h4><p>Need to operate on a reference to something? All 3 languages provide this ability but in different ways. In C# there is a ref and out keywords for achieving this. Pointers are also supported in C#.</p><p>In Kotlin and Java any kind of a reference wrapper can be used, that is in fact just a class that holds a value. Probably the most common reference holders in Kotlin/Java are WeakReference and AtomicReference.</p><h4>Returning multiple values</h4><p>Functions that return more than one value as a result can be useful in development.</p><p>In Kotlin it’s achievable via Pair, Triple, and destructuring declarations.</p><pre>fun getSomething() = Pair(1, 2f)</pre><p>Java can return only 1 value from a method. In this case an array or List as the returning value can be used as a workaround.</p><p>C# can easily return multiple values (typles).</p><pre>public (int, float) GetSomething() =&gt; (1, 2f);</pre><h4>Extension functions</h4><p>Extensions are very convenient in case of performing some operations on some value. Kotlin and C# have extension functions, whereas Java doesn’t.</p><p>Of course, Java community is missing this functionality and in general, it can be achieved with compiler plugins like <a href="https://github.com/manifold-systems/manifold">Manifold</a>.</p><h4><strong>Interoperability</strong></h4><p>Kotlin and Java are interoperable, which means that you can use Kotlin/JVM code in Java projects and vice versa.</p><p>C# is not interoperable with Java or Kotlin because it doesn’t use JVM.</p><h4>There’s so much more</h4><p>Of course, there are a lot of differences that were not mentioned here. But as we just saw, these 3 languages have a lot of features and concepts in common.</p><p>Also, languages evolve and adopt new features from each other. For example, in early versions of Java and C# there were not many concerns about null safety but now there are tools for solving nullable-related issues.</p><p>Feel free to add your comparison in the comments.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11b6e2f1287" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/kotlin-java-and-c-differences-and-similarities-f11b6e2f1287">Kotlin, Java, and C#. Differences and Similarities.</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android ViewModel: Single state or not?]]></title>
            <link>https://proandroiddev.com/android-viewmodel-single-state-or-not-d914f962d44c?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d914f962d44c</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 15:56:37 GMT</pubDate>
            <atom:updated>2024-01-22T15:56:37.230Z</atom:updated>
            <content:encoded><![CDATA[<p>In the Android/Kotlin world, there are 2 ways to provide the state from the ViewModel layer to the View layer: <strong>single state</strong> and <strong>multiple states</strong>. Which one is better? Let’s do some overview of the pros and cons of both methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZG_89oAevhm1vvxT7GLRw.png" /></figure><h4>High-level thoughts</h4><p><strong>Single state</strong> is nice at first glance. A single data class contains all fields, ensuring a consistent state. However, it requires additional effort under the hood: if there are several data sources for the state, then you need a synchronized section to update the state. Otherwise, you may end up with some concurrency-related issues. Also, this way may cause excessive updates or equality checks in the View layer, especially if we are talking about Jetpack Compose.</p><p>On the other hand, <strong>multiple states</strong> provide a more verbose external contract for ViewModel but there is no need for additional synchronization, each data field is independent by default, and Jetpack Compose can read state exactly where it’s needed.</p><h4>The case</h4><p>Let’s do a comparison on a small screen with 3 variables:</p><ul><li>Title</li><li>Text from a text field</li><li>Loading state</li></ul><p>When the screen opens, 2 data sources are loaded: title and text. During loading, the loading state must be true. Additionally, the text can be changed based on user input.</p><h4>Code comparison</h4><p>💡 Note: I’ll try to keep this as simple as possible. For this reason I won’t use redux-like methods. There are also other simplifications, such as no error handling. Please let me know in the comments if you think anything could be improved in this comparison.</p><p>💡 Note: I’ll skip the View layer to keep this article short.</p><p>One thing that will be constant for both cases is repository. With some simplifications, it will be like this:</p><pre>class SomeRepository {<br><br>    suspend fun getTitle(): String {<br>        delay(500)<br>        return &quot;Some Title&quot;<br>    }<br><br>    suspend fun getSavedFieldText(): String {<br>        delay(1000)<br>        return &quot;Saved Field Text&quot;<br>    }<br>}</pre><p>It’s just a stub that emulates some data loading. Now let’s move to the interesting part.</p><h4>Single State</h4><p>Screen state object:</p><pre>data class ScreenState(<br>    val title: String,<br>    val text: String,<br>    val isLoading: Boolean,<br>) {<br>    companion object {<br>        fun default() = ScreenState(<br>            title = &quot;&quot;,<br>            text = &quot;&quot;,<br>            isLoading = false,<br>        )<br>    }<br>}</pre><p>ViewModel:</p><p>💡 Note: I write the state as Flow because ViewModel should not deal with View layer entities like State from Compose.</p><pre>class SomeViewModel(<br>    private val someRepository: SomeRepository,<br>) : ViewModel() {<br><br>    private val _screenState = MutableStateFlow(ScreenState.default())<br>    val screenState: StateFlow&lt;ScreenState&gt; = _screenState<br><br>    // Note: no more public fields here!<br><br>    private val _titleIsLoading = MutableStateFlow(false)<br>    private val _textIsLoading = MutableStateFlow(false)<br><br>    private val stateLock = Mutex()<br><br>    init {<br>        observeLoadingState()<br>        loadTitle()<br>        loadSavedFieldText()<br>    }<br><br>    fun onTextChanged(newValue: String) {<br>        viewModelScope.launch {<br>            updateState {<br>                copy(text = newValue)<br>            }<br>        }<br>    }<br><br>    private fun loadTitle() {<br>        viewModelScope.launch {<br>            _titleIsLoading.value = true<br>            val title = someRepository.getTitle()<br>            _titleIsLoading.value = false<br>            updateState {<br>                copy(title = title)<br>            }<br>        }<br>    }<br><br>    private fun loadSavedFieldText() {<br>        viewModelScope.launch {<br>            _textIsLoading.value = true<br>            val text = someRepository.getSavedFieldText()<br>            _textIsLoading.value = false<br>            updateState {<br>                copy(text = text)<br>            }<br>        }<br>    }<br><br>    private fun observeLoadingState() {<br>        viewModelScope.launch {<br>            _titleIsLoading<br>                .combine(_textIsLoading) { titleIsLoading, textIsLoading -&gt;<br>                    titleIsLoading || textIsLoading<br>                }<br>                .collect { isLoading -&gt;<br>                    updateState {<br>                        copy(isLoading = isLoading)<br>                    }<br>                }<br>        }<br>    }<br><br>    private suspend fun updateState(updater: ScreenState.() -&gt; ScreenState) {<br>        stateLock.withLock {<br>            _screenState.value = _screenState.value.updater()<br>        }<br>    }<br>}</pre><p>Pros:</p><ul><li>You can always find the state of the whole screen in one place.</li><li>Easy to write tests for the state.</li></ul><p>Cons:</p><ul><li>Additional code to keep the state synchronized.</li><li>Excessive copying of all fields when only one field was updated.</li></ul><h4>Multiple States</h4><p>Screen state object:</p><p><em>Not this time. Fields are inside ViewModel.</em></p><p>ViewModel:</p><pre>class SomeViewModel(<br>    private val someRepository: SomeRepository,<br>) : ViewModel() {<br><br>    private val _title = MutableStateFlow(&quot;&quot;)<br>    val title: StateFlow&lt;String&gt; = _title<br><br>    private val _text = MutableStateFlow(&quot;&quot;)<br>    val text: StateFlow&lt;String&gt; = _text<br><br>    private val _isLoading = MutableStateFlow(false)<br>    val isLoading: StateFlow&lt;Boolean&gt; = _isLoading<br><br>    private val _titleIsLoading = MutableStateFlow(false)<br>    private val _textIsLoading = MutableStateFlow(false)<br><br>    init {<br>        observeLoadingState()<br>        loadTitle()<br>        loadSavedFieldText()<br>    }<br><br>    fun onTextChanged(newValue: String) {<br>        _text.value = newValue<br>    }<br><br>    private fun loadTitle() {<br>        viewModelScope.launch {<br>            _titleIsLoading.value = true<br>            val title = someRepository.getTitle()<br>            _titleIsLoading.value = false<br>            _title.value = title<br>        }<br>    }<br><br>    private fun loadSavedFieldText() {<br>        viewModelScope.launch {<br>            _textIsLoading.value = true<br>            val text = someRepository.getSavedFieldText()<br>            _textIsLoading.value = false<br>            _text.value = text<br>        }<br>    }<br><br>    private fun observeLoadingState() {<br>        viewModelScope.launch {<br>            _titleIsLoading<br>                .combine(_textIsLoading) { titleIsLoading, textIsLoading -&gt;<br>                    titleIsLoading || textIsLoading<br>                }<br>                .collect { isLoading -&gt;<br>                    _isLoading.value = isLoading<br>                }<br>        }<br>    }<br><br>    // Note: no state sync and copying here!<br>}</pre><p>Pros:</p><ul><li>Each field is independent from each other by default. <a href="https://www.google.com/search?q=low+coupling+high+cohesion">Low coupling</a>.</li><li>No need in excessive sync sections and fields copying.</li><li>Optimised for Jetpack Compose: it will read .value exactly where it’s needed, not on the highest possible level of composition.</li></ul><p>Cons:</p><ul><li>External contract of ViewModel becomes a bit more verbose.</li><li>Unit tests become a bit less concise.</li></ul><h4>Conclusion</h4><p>Both methods have pros and cons and both methods work. One makes the external contract more concise, the other reduces the coupling within the ViewModel.</p><p>I’ve worked with both approaches, and it’s important to know that, as always, there are trade-offs.</p><p>Please share your thoughts and your cases in the comments.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d914f962d44c" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-viewmodel-single-state-or-not-d914f962d44c">Android ViewModel: Single state or not?</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[Should you use Jetpack Compose?]]></title>
            <link>https://medium.com/mobilepeople/should-you-use-jetpack-compose-02a4d6856fe0?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/02a4d6856fe0</guid>
            <category><![CDATA[android-ui]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 10:04:10 GMT</pubDate>
            <atom:updated>2023-11-23T10:04:10.826Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reasons for and against Jetpack Compose in Android development.</h4><p>Are you used to the good old View system? Or maybe you learn Android development and you are overwhelmed by tons of materials when some of them tell you how to write XML layouts and others show you completely different Jetpack Compose?</p><p>After a year of using Jetpack Compose in production, I want to make a quick recap. Basically, in 2023 you can do the same things on both technologies in 98% of cases, so here we will focus on another type of thoughts. I hope it will make the choice clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbN-uSHZG_MdHp9Vn8ulmw.png" /></figure><h3>Why use</h3><h4>Another level of flexibility</h4><p>Usually, in XML it takes some effort to change the existing layout. <br>For example, If you need to add a View to the layout, you have to create a View object, you have to add it once and track the state of addition to not add it twice.</p><p>On the other hand, in Compose having/not having an element costs you literally one if or similar logic.</p><p>Of course, with the View system, we can always set visibility as gone, but in Compose we can just skip the existence of an element with the same ease.</p><p>After some time of using this new system your way of thinking changes too. You literally may want to write something that you had no time or energy to do before.</p><h4>Google actively promotes it</h4><p>We saw the same story with Java/Kotlin. Nowadays Java has quite limited scope of application in typical Android development. Looks like it’s the same with Compose. Google has invested quite a lot in Jetpack Compose since it was <a href="https://android-developers.googleblog.com/2020/08/announcing-jetpack-compose-alpha.html">in alpha in 2020</a>.</p><p>Google even has <a href="https://developer.android.com/jetpack/compose#apps-built-with-compose">a list of companies that use Jetpack Compose</a>. Some well-known companies like Lyft and Reddit are listed there.</p><h4>It’s multiplatform. Kind of</h4><p>Limited but promising. The last major piece of Kotlin multiplatform puzzle that may make it a big player like Flutter or React Native. It works on a desktop. iOS support is in the alpha stage but the direction is clear.</p><p>The fact that you already can apply your knowledge of writing Android UI to make desktop applications opens some new doors. Imagine if one day you can just compile your Android app as an iOS app with no or little effort.</p><p><a href="https://www.jetbrains.com/lp/compose-multiplatform/">Here you can see supported platforms.</a></p><h3>Why maybe not</h3><h4>Huge legacy Android codebase and you can’t invest time in it.</h4><p>Not every project can afford to put a lot of time into migration to new technology if the previous works well. Also, it may be hard to accept the fact that all the knowledge that you acquired through years of hard work with the View-based system is now not necessary. But it happens in our industry.</p><p>Fortunately, as one of the possible migration strategies you can start implementing Compose step by step only in new screens inside Fragments or Activities.</p><h4>You rely on Custom Views</h4><p>Using a library that provides View-based functionality?<br>Have something like custom charts or fancy animated logic in your codebase? Be prepared to spend extra time rewriting it with new principles.</p><p>Fortunately, <a href="https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose">you can use such Views inside Compose</a>.</p><h4>You want to achieve maximum performance on a low-level</h4><p>Although <a href="https://developer.android.com/jetpack/compose/migrate/compare-performance">Google shows good samples of performance</a>, it may be that in your case you utilize some features of the View system that can make it more beneficial than Compose. For example, you count every byte of your APK and use default Views from the platform. Or maybe you draw using OpenGL on SurfaceView and you just don’t need something else.</p><h3>Conclusion</h3><p>These were some high-level points to think about if you are not sure what to choose. While the technology appears modern and promising, the final decision should be tailored to the specific needs of the project. Feel free to add your thoughts in the comments if you have some scenarios.</p><p>By the way, <a href="https://developer.android.com/jetpack/compose/why-adopt">this is how Google describes why to use Compose</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02a4d6856fe0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/should-you-use-jetpack-compose-02a4d6856fe0">Should you use Jetpack Compose?</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration of Android library to Kotlin Multiplatform]]></title>
            <link>https://medium.com/mobilepeople/migration-of-android-library-to-kotlin-multiplatform-d3b7e7e18f44?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b7e7e18f44</guid>
            <category><![CDATA[maven-central]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 12:03:04 GMT</pubDate>
            <atom:updated>2023-07-25T12:55:39.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2XhkCidRfbbsBut3" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I went through a process of migration with my Android/Kotlin lib, so here is a quick overview with possible issues you may encounter.</p><h4>Why?</h4><p>Let’s start with the reason. Nowadays the vast majority of native Android projects are written in Kotlin. And Kotlin can be used beyond Android. So basically you can write your code once and run it on iOS, desktop and <a href="https://kotlinlang.org/docs/multiplatform.html">other platforms</a>. If you already have your code in Kotlin, it may be quite easy to shift to Multiplatform.</p><h4>Pitfalls</h4><ol><li>First of all it’s necessary to eliminate all Java dependencies (imports) from your code. We just don’t have Java libraries in Kotlin Multiplatform. Of course it may be a huge drawback if your core functionality is related to Android/Java code. In this case you will probably spend some time writing <a href="https://kotlinlang.org/docs/multiplatform-connect-to-apis.html">expect/actual</a> connections.</li><li>KMP is still in <a href="https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html">Beta stage</a> (July 2023). So maybe not everyone can afford this by internal policy. The caption on site states: <br>“Kotlin Multiplatform is in <a href="https://kotlinlang.org/docs/components-stability.html">Beta</a>. It is almost stable, but migration steps may be required in the future. We’ll do our best to minimize any changes you have to make.”</li><li>If you use <a href="https://jitpack.io/">JitPack </a>for publishing your library, you have to migrate to Maven Central. JitPack is a really easy option but it doesn’t support KMP. The issue is open since 2019: <a href="https://github.com/jitpack/jitpack.io/issues/3853">https://github.com/jitpack/jitpack.io/issues/3853</a></li><li>iOS support. You need a Mac. <a href="https://kotlinlang.org/docs/multiplatform-mobile-setup.html">Documentation </a>says: <br>“To write iOS-specific code and run an iOS application on a simulated or real device, you’ll need a Mac with macOS. This cannot be performed on other operating systems, such as Microsoft Windows. This is an Apple requirement”<br>💡 Hint: This can be partially mitigated by using third-party build systems like GitHub Actions with <a href="https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources">macOS runner</a>.</li></ol><h3>The migration</h3><h4>Project modification</h4><p>I started with a creation of a new Multiplatform Library project as a template in IDEA. This step is described really well in the <a href="https://kotlinlang.org/docs/multiplatform-library.html#create-a-project">documentation here</a>. Of course, you can modify your project structure and build scripts manually but in my case, it was easier to just use the template.</p><p>After that, I copied my existing Kotlin code into <strong>commonMain </strong>folder<strong> </strong>and then I saw all compatibility errors that needed to be fixed. <br>In my case there were several issues: <br>- Absence of <strong>System.currentTimeMillis()</strong> function in KMP. <br>- Absence of <strong>Dispatchers.IO</strong> by default.<br>- No <strong>JUnit</strong> for tests.<br>- No <strong>java.util.concurrent.atomic.*</strong> package.</p><p>When every issue was solved and tests became green, I deleted almost everything (don’t remove Git files!) from the folder in my original project’s location and copied the new structure into that. Luckily Git was smart enough to detect files movements so in most cases it was an easy-to-read diff.</p><h4>From JitPack to Maven Central</h4><h4>1. Sonatype</h4><p>First of all, you need a Sonatype account. And to get it you have to create a task <a href="https://issues.sonatype.org/secure/Dashboard.jspa">here</a>. More details about account creation <a href="https://getstream.io/blog/publishing-libraries-to-mavencentral-2021/#registering-a-sonatype-account">here</a>.</p><blockquote>If you don’t have a dedicated web-site with a domain, it’s not a problem. You can use your GitHub address instead.</blockquote><h4><strong>2. </strong>GPG Key</h4><p>Next, you need to create a GPG Key Pair for signing your library. It may be generated in several ways depending on your OS. Don’t forget to upload the public part of your key to the server like this: <br>gpg --keyserver keyserver.ubuntu.com --send-keys 5BEF072A.</p><h4><strong>3. </strong>Publication script</h4><p>After the steps above you need to set up your publication script. If you use <strong>kts</strong> scripts, <a href="https://kotlinlang.org/docs/multiplatform-library.html#set-up-publication">this instruction</a> should work for you.</p><blockquote>Make sure you don’t add secret files to your Git history. Use <strong>.gitignore</strong> file. And make a separate backup of secret files.</blockquote><p>One thing that is missed in the instruction above is that you also have to add a <strong>settings.gradle.kts</strong> file with one line: <br>rootProject.name = <strong>“convention-plugins” <br></strong>into convention-plugins folder too because it’s basically a separate Gradle project.</p><h4><strong>4. Publish to Sonatype</strong></h4><p>The last step on IDE side is publication. To publish your library you have to invoke <strong>publishAllPublicationsToSonatypeRepository</strong> Gradle task.</p><p>Here you can face an error that wasn’t described in the instruction above. It may look like: <br>Task ‘:publishIosArm64PublicationToSonatypeRepository’ uses this output of task ‘:signIosX64Publication’ without declaring an explicit or implicit dependency<br>In this case, you can manually declare dependencies between tasks with <strong>dependsOn</strong> function or automate it all at once like it’s suggested in <a href="https://youtrack.jetbrains.com/issue/KT-46466">the issue</a>.</p><h4>5. Release to Maven Central</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4rAwQzatFmGiWTVX51ORQ.png" /></figure><p>Log-in into <a href="https://s01.oss.sonatype.org/#stagingRepositories">Nexus repository manager</a> and let the system check your publication by pressing “Close” button. If everything is OK — release it to Maven Central via “Release” button. Soon after, everyone will be able to find your library on Maven. Good job!</p><h4>Extra step. Automation</h4><p>If you build your library often enough — think about build/publication automation. Nowadays GitHub Actions may be a good choice with a free quota.</p><h3>Conclusion</h3><p>Kotlin Multiplatform looks promising and it may be a good idea to increase the reach of your Android library with relatively little effort. It took me 2 evenings to migrate my project to KMP and the only drawback for me is the necessity to do a more complicated release process compared to JitPack.</p><p>By the way, here is the library that I’m talking about. If you think about the efficiency of your caching logic, try it:</p><ul><li><a href="https://medium.com/@andrei_r/easy-caching-android-kotlin-flow-b824a29e8a77">Easy caching Android + Kotlin + Flow</a></li><li><a href="https://github.com/Andrew0000/Universal-Cache">GitHub - Andrew0000/Universal-Cache: Kotlin Flow caching and request sharing. Main idea: don&#39;t request data more times than it&#39;s needed. Made for Kotlin Multiplatform + Coroutines + Flow.</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b7e7e18f44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/migration-of-android-library-to-kotlin-multiplatform-d3b7e7e18f44">Migration of Android library to Kotlin Multiplatform</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Picker on Android. What suits your needs?]]></title>
            <link>https://medium.com/mobilepeople/image-picker-on-android-what-suits-you-needs-975ccc142d6d?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/975ccc142d6d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Wed, 10 May 2023 11:57:00 GMT</pubDate>
            <atom:updated>2023-05-11T11:19:02.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AO1OQrenR02s79s_" /><figcaption>Photo by <a href="https://unsplash.com/@invictar1997?utm_source=medium&amp;utm_medium=referral">Soragrit Wongsa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s imagine a typical case in Android/Kotlin development when you need to make the functionality of sending an image to a back-end. It could be a user’s profile image or an image that the user wants to send into a chat or something else. So how can we implement it?</p><p>Obviously, we have the <a href="https://developer.android.com/training/data-storage/shared/photopicker">Photo Picker from Google</a>, right? It works, everything is good, end of the story.</p><p>Well, not really. Let’s elaborate on the use case a bit.</p><h4>1. Do we need a choice between a gallery and a camera?</h4><p>If you need a camera then Photo Picker from Google can’t help you. And here we have at least 2 options:</p><ul><li>Implement an in-app camera with <a href="https://developer.android.com/training/camerax">CameraX</a> or similar libraries. In this way, you’ll partially duplicate the capability of the system camera in your app.</li><li>Ask the system to <a href="https://developer.android.com/training/camera-deprecated/photobasics">take a photo</a>. In this case, you just use the system camera and it provides you the result.</li></ul><p>Let’s focus on the second option for now. It’s easy to implement and it doesn’t even require you to declare the <em>android.permission.CAMERA</em> permission in your AndroidManifest (But if you declare it then you need to ask a runtime permission).</p><p>Basically, there are 3 steps to implement it:</p><ul><li>Declare a <a href="https://developer.android.com/reference/androidx/core/content/FileProvider">FileProvider</a> in your app that will receive the result from the system.</li><li>Launch the intent with action <a href="https://developer.android.com/reference/android/provider/MediaStore#ACTION_IMAGE_CAPTURE">MediaStore.ACTION_IMAGE_CAPTURE</a>.</li><li>Get the result in onActivityResult() or <a href="https://developer.android.com/training/basics/intents/result#custom">StartActivityForResult</a> callback.</li></ul><p>So it’s quite simple solution if you don’t need to include the real-time camera preview into your app.</p><blockquote>Note: The documentation in <a href="https://developer.android.com/training/camera-deprecated/photobasics#TaskPath">this</a> link is marked as deprecated but it looks more like a mistake in the documentation. Because the idea of deprecation is related to Camera-1 approach which now is suggested to replace with CameraX. But MediaStore.ACTION_IMAGE_CAPTURE is a different approach and works well.</blockquote><h4>2. Do we need to have the possibility to crop or rotate the image before sending it?</h4><p>Obviously not every image from the gallery or especially the camera is ideal. Users may want to edit the image before providing it to your app.</p><p>Sounds complicated? Don’t worry, we can use the power of Android community. My personal choice for now is <a href="https://github.com/Yalantis/uCrop">uCrop library</a>. It provides basic editing options, for example: crop, rotate, and limit the output size.</p><p>And it has pretty friendly syntax, like this:</p><pre>UCrop.of(sourceUri, destinationUri)<br>    .withAspectRatio(16, 9)<br>    .withMaxResultSize(maxWidth, maxHeight)<br>    .start(context)</pre><h4>3. What are the limitations of Photo Picker from Google?</h4><p>Basically, it works via Google Play services but if this functionality isn’t available on some devices then <a href="https://developer.android.com/reference/kotlin/android/content/Intent#action_open_document">ACTION_OPEN_DOCUMENT</a> will be used instead.</p><p>Let’s look at the code.</p><p>The typical usage of Photo Picker from Google:</p><pre>val pickMedia = registerForActivityResult(PickVisualMedia()) { uri -&gt;<br>    // Process result from Uri<br>}<br><br>pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly))</pre><p>The typical usage of ACTION_OPEN_DOCUMENT for image selection:</p><pre>val launcher = activity.registerForActivityResult(StartActivityForResult()) {<br>    val uri = it.data?.data<br>    // Process result from Uri<br>}<br><br>val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {<br>    type = &quot;image/*&quot;<br>    addCategory(Intent.CATEGORY_OPENABLE)<br>    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)<br>}<br><br>launcher.launch(intent)</pre><p>So if the approach with ACTION_OPEN_DOCUMENT is not much more difficult then what is the value of Photo Picker from Google? Well, it provides some UI and handles the interactions with the file system. It allows us to not declare storage permissions. On the other hand, the approach with ACTION_OPEN_DOCUMENT has the same features and a bit more.</p><p>Can Photo Picker from Google get a picture from Google Drive or OneDrive? It’s not mentioned in the documentation and as I tested — No.</p><p>Can ACTION_OPEN_DOCUMENT get a picture from such cloud providers? Yes.</p><blockquote>The idea of <a href="https://developer.android.com/reference/kotlin/android/content/Intent#action_open_document">ACTION_OPEN_DOCUMENT</a> is wider than your local file system. The file system is just one of many possible providers here.</blockquote><p>In other words, Photo Picker from Google provides a new UI and a few lines shorter integration. But it doesn’t have the ability to get a content from a cloud provider (at least in May 2023). Not good, not bad.</p><h4>I just want to get a photo from a gallery or camera, do I really need to keep in mind all of this?</h4><p>Thanks to the power of Android community again, there are some ready-to-use libraries. But some of them are abandoned so eventually I made my own library to handle my needs. It’s based on ACTION_OPEN_DOCUMENT for Gallery source and ACTION_IMAGE_CAPTURE for the Camera source.</p><p>Main functionality:</p><ul><li>Pick a picture from the gallery without storage permission</li><li>Take a photo from the camera (camera permission is optional)</li><li>Rotate or crop the captured image</li><li>Save the final image to app’s local directory so you can use it like a File, without a ContentResolver</li><li>Transform the result to Jpeg / PNG / WebP automatically if needed</li></ul><p>An example of usage:</p><pre>val launcher = registerForActivityResult(StartActivityForResult()) {<br>    it?.data?.data?.let { uri -&gt;<br>        // Done. Use the received uri with captured image inside.<br>        imageView.setImageURI(uri)<br>    }<br>}<br><br>ImagePickerPlus<br>    .createIntent(<br>        activity = this,<br>        PickRequest(<br>            source = PickSource.GALLERY, // or PickSource.CAMERA<br>            transformation = ImageTransformation(<br>                maxSidePx = 1024, // Or -1 if limit isn&#39;t needed<br>                encodeToFormat = ImageFormat.JPEG, // Or null is transformation isn&#39;t needed<br>            ),<br>        )<br>    )<br>    .let { launcher.launch(it) }</pre><p>Check it out and leave feedback:</p><p><a href="https://github.com/Andrew0000/ImagePickerPlus">GitHub - Andrew0000/ImagePickerPlus: Simple photo picker for Android. Can get an image from gallery or camera without runtime permissions.</a></p><h4>Advanced mode. Your self-made solution</h4><p>If nothing suits you and you decide to write everything by yourself then let me share some pitfalls that you have to be aware of:</p><ul><li>Images can be large. Sometimes you can’t just pass a bitmap as is without risk of OutOfMemoryError. It’s a good idea to use proper methods of resizing like it’s described in the <a href="https://developer.android.com/topic/performance/graphics/load-bitmap">documentation</a>.</li><li>Images can be passed to you in a rotated state. So you have to detect the rotation using <a href="https://developer.android.com/reference/android/media/ExifInterface">ExifInterface</a>.</li><li>There are many possible images format. But probably you want to focus only on main like Jpeg, PNG, WebP.</li><li>When you receive an Uri as a result of an image picker, it may not always be an ordinary File. Sometimes it has a content:// scheme and you have to handle it via <a href="https://developer.android.com/reference/android/content/ContentResolver">ContentResolver</a>. In fact, it’s more reliable to handle all Uri via ContentResolver.</li></ul><h4>Conclusion</h4><p>There is more than one way to implement the photo picker functionality in your app.</p><ul><li>If you need a modern UI for the latest Androids and cloud providers are not needed then Photo Picker from Google is OK.</li><li>Need to have cloud providers? Don’t want to depend on Play Services? Consider using ACTION_OPEN_DOCUMENT with mime filters.</li><li>Something even more complicated like post-processing and the ability to use a camera along with a gallery? Try to find a library that suits your needs or write this functionality by yourself.</li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975ccc142d6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/image-picker-on-android-what-suits-you-needs-975ccc142d6d">Image Picker on Android. What suits your needs?</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to retry network requests automatically in Android + Kotlin]]></title>
            <link>https://medium.com/mobilepeople/how-to-retry-network-requests-automatically-in-android-kotlin-64dcafb7f294?source=rss-ff1606e3bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/64dcafb7f294</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[okhttp]]></category>
            <dc:creator><![CDATA[Andrei Riik]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 09:13:32 GMT</pubDate>
            <atom:updated>2023-03-14T12:07:22.262Z</atom:updated>
            <content:encoded><![CDATA[<h4>3 popular ways in 2023: RxJava / Coroutines / OkHttp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oueSQ9fiE-spAYmf" /><figcaption>Photo by <a href="https://unsplash.com/@mike_van_den_bos?utm_source=medium&amp;utm_medium=referral">Mike van den Bos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the pitfalls we should keep in mind when adding every new feature to our mobile apps is the error handling. As part of this, we have to remember that mobile internet quality can be very different even within big cities. There are buildings with thick walls and there are tunnels. Add to this possible back-end internal errors and things become not so straightforward as we could want.</p><p>One of the possible solutions to such issues is automatic retrying for failed requests. Mainly it includes 3–5 retries with increasing delay for each next retry. We need this increasing delay to mitigate the risk of spamming our back end if something goes wrong with it.</p><p>Of course automatic retries don’t prevent us from showing some kind of “retry button” for user if all retries fail, as well as implementing other possible strategies like reacting on internet availability. But let’s focus on the first option in this article.</p><h3>Requirements for solution</h3><p>What kind of solution may we want as developers?</p><ul><li>Easy to use. One-line wrapper is ideal. Or even global configuration on the network layer.</li><li>Customizable. We may want to implement different retry strategies for different errors.</li><li>Fits our tech stack. Of course, we don’t want to migrate from RxJava to Coroutines or vice versa just because of a particular solution.</li></ul><p>In this article I’ll share how to implement a retrying with:</p><ul><li>RxJava</li><li>Kotlin Coroutines</li><li>OkHttp interceptors</li></ul><h3>RxJava</h3><p>Everything is a stream. Even errors.</p><p>There are many ways to implement the desired behaviour in Rx. In this solution we will use <strong>.retryWhen()</strong> function because it gives more flexibility than just plain<strong> </strong><strong>.repeat()</strong> and easier then custom <strong>Observable</strong>.</p><p>It’s a bit tricky function, but the main idea is: we should “map” it to <strong>Observable.error</strong> only if we want to pass an error to the downstream, otherwise it will re-subscribe to the upstream.</p><p>This interface of retrying function fits most needs:</p><pre>fun &lt;T : Any&gt; Observable&lt;T&gt;.withRetrying(<br>    fallbackValue: T?,<br>    tryCnt: Int,<br>    intervalMillis: (attempt: Int) -&gt; Long,<br>    retryCheck: (Throwable) -&gt; Boolean,<br>): Observable&lt;T&gt;</pre><p>We can specify:</p><ul><li><strong>fallbackValue — </strong>value to emit if all retries ended with failure. Or null if we are ready to handle an error somewhere in downstream.</li><li><strong>tryCnt — </strong>is how many times in total we will try to request and re-request.</li><li><strong>intervalMillis </strong>— is a lambda in which we can implement the increasing delay.</li><li><strong>retryCheck </strong>— is a lambda in which we can decide whether we need to retry this particular error or not. Usually, network errors and 5xx HTTP codes are subjects to retry, but 4xx codes are not.</li></ul><p>And the implementation:</p><pre>fun &lt;T : Any&gt; Observable&lt;T&gt;.withRetrying(<br>    fallbackValue: T?,<br>    tryCnt: Int,<br>    intervalMillis: (attempt: Int) -&gt; Long,<br>    retryCheck: (Throwable) -&gt; Boolean,<br>): Observable&lt;T&gt; {<br>    if (tryCnt &lt;= 0) {<br>        return this<br>    }<br>    return this<br>        .retryWhen { errors -&gt;<br>            errors<br>                .zipWith(<br>                    Observable.range(1, tryCnt)<br>                ) { th: Throwable, attempt: Int -&gt;<br>                    if (retryCheck(th) &amp;&amp; attempt &lt; tryCnt) {<br>                        Observable.timer(intervalMillis(attempt), TimeUnit.MILLISECONDS)<br>                    } else {<br>                        Observable.error(th)<br>                    }<br>                }<br>                .flatMap { it }<br>        }<br>        .let {<br>            if (fallbackValue == null) {<br>                it<br>            } else {<br>                it.onErrorResumeNext { Observable.just(fallbackValue) }<br>            }<br>        }<br>}</pre><p>Basically, it’s an evolution of what is described as an example in the documentation for the<strong>.retryWhen()</strong> <a href="https://github.com/ReactiveX/RxJava/blob/ed674be204210fe0804d64e28fdd356745915048/src/main/java/io/reactivex/rxjava3/core/Observable.java#L12003">function</a>.</p><p>Also, it’s a good idea to write additional wrappers for <strong>Single</strong> and other stream types:</p><pre>fun &lt;T : Any&gt; Single&lt;T&gt;.withRetrying(<br>    fallbackValue: T?,<br>    tryCnt: Int,<br>    intervalMillis: (attempt: Int) -&gt; Long,<br>    retryCheck: (Throwable) -&gt; Boolean,<br>): Single&lt;T&gt; = this<br>    .toObservable()<br>    .withRetrying(fallbackValue, tryCnt, intervalMillis, retryCheck)<br>    .firstOrError()</pre><p>For further simplification, it can be wrapped to project-common functions. For instance, if your common policy is to retry 3 times with increasing delay, it will be like this:</p><pre>fun &lt;T : Any&gt; Single&lt;T&gt;.commonRetrying(fallbackValue: T? = null) =<br>    withRetrying(fallbackValue, 3, { 2000L * it }, networkRetryCheck)<br><br>private val networkRetryCheck: (Throwable) -&gt; Boolean = {<br>    val shouldRetry = when {<br>        it.isHttp4xx() -&gt; false<br>        else -&gt; true<br>    }<br>    shouldRetry<br>}</pre><h4>Final usage example</h4><p>Somewhere in your repository layer, it’s exactly plus one extra line:</p><pre>fun getSomething(params: String): Single&lt;YourResponseType&gt; =<br>    api.getSomething(params)<br>        .commonRetrying()</pre><h3>Kotlin Coroutines</h3><p>We can use basically the same interface parameters in coroutines as we discussed in case of Rx. It allows us to configure desired behaviour in the same way as above:</p><pre>suspend fun &lt;T&gt; retrying(<br>    fallbackValue: T?,<br>    tryCnt: Int,<br>    intervalMillis: (attempt: Int) -&gt; Long,<br>    retryCheck: (Throwable) -&gt; Boolean,<br>    block: suspend () -&gt; T,<br>): T {<br>    try {<br>        val retryCnt = tryCnt - 1<br>        repeat(retryCnt) { attempt -&gt;<br>            try {<br>                return block()<br>            } catch (e: Exception) {<br>                if (e is CancellationException || !retryCheck(e)) {<br>                    throw e<br>                }<br>            }<br>            delay(intervalMillis(attempt + 1))<br>        }<br>        return block()<br>    } catch (e: Exception) {<br>        if (e is CancellationException) {<br>            throw e<br>        }<br>        return fallbackValue ?: throw e<br>    }<br>}</pre><p>The algorithm is simple:</p><ul><li>Try <strong>retryCnt</strong> times in a loop and one more time after the loop.</li><li>Check for given <strong>retryCheck</strong> if we need to retry after the particular exception or not. Delay before next try for <strong>intervalMillis</strong> if yes.</li><li>If all tries failed but we have a <strong>fallbackValue</strong> to return —return it. Otherwise, throw the error further.</li></ul><p>Probably the main pitfall in suspend functions like this that makes our code longer than it could be — we need to remember about <strong>CancellationException</strong> and <a href="https://kotlinlang.org/docs/cancellation-and-timeouts.html#cancellation-is-cooperative">its role in Coroutines</a>.</p><p>Also we can unify the solution above to a particular project needs, similar to how we made it with Rx:</p><pre>suspend fun &lt;T&gt; commonRetrying(<br>    fallbackValue: T?,<br>    block: suspend () -&gt; T,<br>): T = retrying(fallbackValue, 3, { 2000L * it }, networkRetryCheck, block)</pre><h4>Final usage example</h4><p>Somewhere in your repository layer, it’s nearly one extra line:</p><pre>suspend fun getSomething() = commonRetrying {<br>    api.getSomething()<br>}</pre><p>By the way, it simply fits <a href="https://medium.com/@andrei_r/easy-caching-android-kotlin-flow-b824a29e8a77">Universal Cache</a>. <br>The following code wraps all our underlying retries to a cached source as if it’s just a single request:</p><pre>val listOfSomething = CachedSourceNoParams(<br>    source = {<br>        commonRetrying {<br>            api.getSomething()<br>        }<br>    }<br>)</pre><p><a href="https://medium.com/@andrei_r/easy-caching-android-kotlin-flow-b824a29e8a77">Easy caching Android + Kotlin + Flow</a></p><h3>OkHttp interceptors</h3><p>Previous solutions are flexible and support a variety of parameters. Also, they can be used not only for network but for any kind of operations or calculations.</p><p>On the other hand, someone can forget to wrap an API-call into such functions. In this case, we can chose to implement retrying logic into the network layer and into OkHttp in particular. But it has some limitations in comparison to previous examples. It’s more difficult to apply a specific retry policy for only particular requests. Also, it will not retry if an error occurs somewhere between network call and the invocation side, for instance on response data parsing phase. Good it or bad — it depends on your project&#39;s needs.</p><p>Basic implementations look like the following. It doesn’t contain a check for 4xx and 5xx HTTP codes, but it also can be implemented.</p><pre>import okhttp3.Interceptor<br>import okhttp3.Response<br><br>class RetryingInterceptor : Interceptor {<br><br>    private val tryCnt = 3<br>    private val baseInterval = 2000L<br><br>    override fun intercept(chain: Interceptor.Chain): Response {<br>        return process(chain, attempt = 1)<br>    }<br><br>    private fun process(chain: Interceptor.Chain, attempt: Int): Response {<br>        var response: Response? = null<br>        try {<br>            val request = chain.request()<br>            response = chain.proceed(request)<br>            if (attempt &lt; tryCnt &amp;&amp; !response.isSuccessful) {<br>                return delayedAttempt(chain, response, attempt)<br>            }<br>            return response<br>        } catch (e: Exception) {<br>            if (attempt &lt; tryCnt &amp;&amp; networkRetryCheck(e)) {<br>                return delayedAttempt(chain, response, attempt)<br>            }<br>            throw e<br>        }<br>    }<br><br>    private fun delayedAttempt(<br>        chain: Interceptor.Chain,<br>        response: Response?,<br>        attempt: Int,<br>    ): Response {<br>        response?.body?.close()<br>        Thread.sleep(baseInterval * attempt)<br>        return process(chain, attempt = attempt + 1)<br>    }<br>}</pre><p>Here we do retry with a delay if: <br><strong>a)</strong> Check for <strong>.isSuccessful</strong> fails<br><strong>b)</strong> An exception occurs</p><p>The important thing here is to not forget to close a previous response body as it’s suggested in the <a href="https://square.github.io/okhttp/features/interceptors/">documentation</a>:</p><blockquote>If chain.proceed(request) is being called more than once previous response bodies must be closed.</blockquote><p>That interceptor can be injected in the following way when you construct your OkHttpClient (which can be passed into a Retrofit configuration):</p><pre>val client = OkHttpClient.Builder()<br>    .addInterceptor(RetryingInterceptor())<br>    .build()</pre><h4>Final usage example</h4><p>Not this time. There are no extra lines on the caller’s side in comparison with previous solutions. Just set it up once and forget.</p><h3>Conclusion</h3><p>As we’ve discussed, it’s a good idea to handle possible network requests instability. It’s the kind of nature of network that we should keep in mind. We just went through 3 solutions, each works a bit different and the decision of what to use depends on your project specifics.</p><p>If you need a single retrying policy for the entire application — OkHttp interceptor is a reasonable choice. If you need more control over specific requests or you need to retry something that doesn’t use OkHttp under the hood — the decision depends on your tech stack. Nowadays, it’s usually RxJava or Kotlin Coroutines. Both of them are flexible enough for this task.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64dcafb7f294" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/how-to-retry-network-requests-automatically-in-android-kotlin-64dcafb7f294">How to retry network requests automatically in Android + Kotlin</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>