<?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 Roman Kamyshnikov on Medium]]></title>
        <description><![CDATA[Stories by Roman Kamyshnikov on Medium]]></description>
        <link>https://medium.com/@rkam88?source=rss-bc0767d43086------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-HegjXexv3V5ayO41_weA.jpeg</url>
            <title>Stories by Roman Kamyshnikov on Medium</title>
            <link>https://medium.com/@rkam88?source=rss-bc0767d43086------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:43:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rkam88/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[Automate screenshot testing for Compose previews via reflection]]></title>
            <link>https://proandroiddev.com/automate-screenshot-testing-for-compose-previews-via-reflection-e6eb0f8fd977?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6eb0f8fd977</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 01:54:11 GMT</pubDate>
            <atom:updated>2023-09-12T01:54:11.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4GuWFZYF8ZNL1Eedf1Thg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/HcmdstM9IFw">Lina Castaneda</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Screenshot testing is a valuable technique to validate UI and prevent regressions when updating existing screens or components. Yet, as with any kind of testing it has the drawback of requiring a significant time investment to write and maintain the tests.</p><h4>Showkase</h4><p>One way to automate screenshot testing is by using <a href="https://github.com/airbnb/Showkase/">Showkase</a>, a library by Airbnb created to generate a component browser which additionally allows to <a href="https://github.com/airbnb/Showkase/pull/294">automatically</a> test all methods annotated with <strong>@Preview</strong> using Paparazzi. Unfortunately, this requires you to add Showkase as a dependency for each module that has any previews you want covered with tests and because Showkase relies on code generation, which will increase the build time for all those modules. So using it just for screenshot tests might not the best solution as it’s not it’s primary function.</p><h4>Reflection</h4><p>Another alternative is to use reflection to find all previews at runtime and dynamically create tests for them. A basic implementation of this approach was previously described in this <a href="https://codedogg.wordpress.com/2023/03/26/compose-paparazzi-automatically-find-preview-composables-at-runtime/">blogpost</a>. This article builds up on the idea described there to provide an improved solution that’s more flexible and covers some additional edge-cases.</p><p>For the tests we’ll use the Paparazzi library developed by Cashapp. Mainly because of the fact that it doesn’t require an emulator to run the tests, which makes them both faster and more reliable.</p><p>That said, the proposed solution can work with other screenshot testing libraries — if you’re curious about alternatives, the absolute best place to look would be this <a href="https://github.com/sergio-sastre/Android-screenshot-testing-playground">Github repository</a> by <a href="https://medium.com/u/e72aad76b3c6">Sergio Sastre</a>, which provides detailed descriptions, implementation examples and a lot of useful information about all the available options for screenshot testing in Android.</p><h3>Example project</h3><p>I’ve implemented the reflection based solution on an example project, forked from the official Now in Android app. Most of the code is in the <a href="https://github.com/rkam88/nowinandroid/blob/main/screenshot-test/src/test/java/com/google/samples/apps/nowinandroid/screenshottest/PreviewTests.kt">PreviewTests class</a> in the screenshot-test module created specifically for the tests. Additionally, some helper annotations and classes where added to the <a href="https://github.com/rkam88/nowinandroid/tree/main/core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/screenshottest">core:ui module</a>.</p><h4>Finding all previews</h4><p>Just as in the original blogpost, we’ll use the <a href="https://github.com/ronmamo/reflections">Reflections library</a> to find all methods annotated with <strong><em>Preview</em></strong>:</p><pre>private fun findPreviewMethodsInCodebase(): Set&lt;Method&gt; {<br>    val configuration = ConfigurationBuilder()<br>        .forPackage(APPLICATION_PACKAGE)<br>        .filterInputsBy(FilterBuilder().includePackage(APPLICATION_PACKAGE))<br>        .addScanners(Scanners.MethodsAnnotated)<br>    val reflections = Reflections(configuration)<br>    return reflections.getMethodsAnnotatedWith(Preview::class.java) +<br>        reflections.getMethodsAnnotatedWith(ThemePreviews::class.java) +<br>        reflections.getMethodsAnnotatedWith(DevicePreviews::class.java)<br>}</pre><p>This method will be used by <strong><em>ComposablePreviewProvider</em></strong> to create a list of <strong><em>ComposablePreview</em></strong>, which we’ll use to run our tests.</p><p>Besides finding all methods with the <strong><em>Preview</em></strong> annotation, we also handle an edge-case: the multipreview annotations <strong><em>ThemePreviews</em></strong> and <strong><em>DevicePreviews</em></strong> used in the Now in Android project. To keep things simple, we’ll treat them just as a regular <strong><em>Preview</em></strong> annotation, but if necessary the code of <strong><em>ComposablePreviewProvider</em></strong> could easily be modified to handle them differently.</p><p>At this point, it’s necessary to select the strategy we’ll use for the automation. I’ve chosen to create tests for all previews (private methods included), but depending on your specific needs you could either generate tests for public previews only or use a custom annotation to explicitly mark the functions that you want tested.</p><p>I find that generating tests for all previews by default works best as the main downside of this is increasing the time required to run the tests. Unless you’re working on a <em>very</em> big project this time is likely to be negligible — in the project this approach was initially implemented over 250 tests take around a minute to run on CI, including time spent building the module.</p><h4>Ignoring previews and Java Dynamic Proxy</h4><p>If you decide to generate tests for all previews, there still might be cases when you want to exclude a preview and a custom <a href="https://github.com/rkam88/nowinandroid/blob/main/core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/screenshottest/IgnoreScreenshotTest.kt"><strong><em>IgnoreScreenshotTest</em></strong> annotation</a> can be used for that purpose.</p><pre>override fun provideValues(): List&lt;ComposablePreview&gt; {<br>    val composablePreviews = mutableListOf&lt;ComposablePreview&gt;()<br><br>    findPreviewMethodsInCodebase()<br>        .filterNot { method -&gt; method.annotations.any { it is IgnoreScreenshotTest } }<br>        .onEach { if (Modifier.isPrivate(it.modifiers)) it.isAccessible = true }<br>        .forEach { method -&gt;<br>            composablePreviews.add(method.toComposablePreview())<br>        }<br><br>    return composablePreviews<br>}</pre><p>After finding all our preview methods, filtering out the ones we want to ignore and making those methods accessible, we can now transform those methods into <strong><em>ComposablePreviews</em></strong>. The reason we need to do that is because the last parameter each method we get via reflection will expect is a <strong><em>Composer</em></strong> interface instance. The <strong><em>Composer</em></strong> parameter links the composable function code we write to the runtime and is added to each method by the compose compiler plugin.</p><p>We can’t access it directly, but we can leverage Java’s Dynamic Proxy and an <strong><em>InvocationHandler </em></strong>to get the <strong><em>Composer</em></strong> instance when invoking out method. If you’re interested in Java Dynamic Proxy, a more detailed explanation of how it works is available in <a href="https://medium.com/rkam88/how-to-mock-retrofit-api-calls-or-any-other-interface-53161eee6789">one of my previous articles</a>.</p><h4>Naming tests</h4><p>To run our tests, we’ll use <strong><em>TestParameterInjector</em></strong>:</p><pre>@RunWith(TestParameterInjector::class)<br>class PreviewTests {<br>    @get:Rule val paparazzi: Paparazzi = PaparazziRuleProvider.get()<br><br>    @Test<br>    fun snapshot(<br>        @TestParameter(valuesProvider = ComposablePreviewProvider::class)<br>        composablePreview: ComposablePreview,<br>    ) {<br>        paparazzi.snapshot { composablePreview() }<br>    }<br>}</pre><p>An important feature about how it works is that it’ll call the <strong><em>toString() </em></strong>method of each parameter we pass to it and use it’s result as a suffix for the name of the test, which will also be the name of the recorded snapshot.</p><p>In order to have a meaningful name, we can override this method when creating the wrapper:</p><pre>private fun Method.toComposablePreview(...): ComposablePreview {<br>    val proxy = Proxy.newProxyInstance(...) as ComposablePreview<br><br>    return object : ComposablePreview by proxy {<br>        override fun toString(): String {<br>            return buildList&lt;String&gt; {<br>                add(declaringClass.simpleName)<br>                add(name)<br>            }.joinToString(&quot;_&quot;)<br>        }<br>    }<br>}</pre><h4>PreviewParameterProvider</h4><p>A very important edge case that needs to be handled before we can start generating screenshots is previews that use <strong>PreviewParameterProvider</strong>.</p><p>To be able to call those and still have meaningful names, we can create a helper class:</p><pre>abstract class NamedPreviewParameterProvider&lt;T&gt; : PreviewParameterProvider&lt;T&gt; {<br>    abstract val nameToValue: Sequence&lt;Pair&lt;String?, T&gt;&gt;<br>    final override val values: Sequence&lt;T&gt;<br>        get() = nameToValue.map { it.second }<br>}<br><br><br>// usage example<br>class ExampleProvider: NamedPreviewParameterProvider&lt;String&gt;() {<br>    override val nameToValue = sequenceOf(<br>        &quot;One&quot; to &quot;1&quot;,<br>        &quot;Two&quot; to &quot;2&quot;,<br>        null to &quot;A parameter that will be ignored for tests&quot;<br>    )<br>}</pre><p>The code in <strong><em>ComposablePreviewProvider.provideValues</em></strong> will check each method to see if it uses parameters with the helper function:</p><pre>private fun Method.findPreviewParameterAnnotation(): PreviewParameter? {<br>    return this.parameterAnnotations<br>        .flatMap { it.toList() }<br>        .find { it is PreviewParameter } as PreviewParameter?<br>}</pre><p>If it does, we can get the class type of the <strong><em>PreviewParameterProvider</em></strong>, create an instance and access it’s values to create several <strong><em>ComposablePreviews</em></strong><em>. </em>We’ll<em> </em>use either the name or index of the parameter as a suffix for the test and snapshot name:</p><pre>val providerAnnotation = method.findPreviewParameterAnnotation()<br><br>if (providerAnnotation == null) { ... } else { <br>    // Create an instance of the PreviewParameterProvider.<br>    val provider = providerAnnotation.provider.createInstanceUnsafe()<br><br>    // Get a sequence with the name and value for each parameter<br>    // that the [Preview] should be called with.<br>    val nameToValue = if (provider is NamedPreviewParameterProvider&lt;*&gt;) {<br>        provider.nameToValue.mapNotNull { (name, value) -&gt;<br>            // ignore previews with a parameter that has null name<br>            if (name == null) return@mapNotNull null<br><br>            name to value<br>        }<br>    } else {<br>        provider.values.mapIndexed { index, value -&gt;<br>            index.toString() to value<br>        }<br>    }<br><br>    // Create a [ComposablePreview] for each name and value pair.<br>    nameToValue.forEach { (nameSuffix, value) -&gt;<br>        composablePreviews.add(method.toComposablePreview(nameSuffix, value))<br>    }<br>}</pre><h4>Custom configuration</h4><p>If any custom configuration is needed for a specific test, a custom annotation can be created and added to the relevant preview:</p><pre>@Target(AnnotationTarget.FUNCTION)<br>annotation class ScreenshotTestParameters(<br>    val renderingMode: TestRenderingMode = TestRenderingMode.SHRINK,<br>)<br><br>enum class TestRenderingMode { NORMAL, SHRINK }</pre><p>After some simple changes to the code in <strong><em>PreviewTests</em></strong>, we can extract any data passed via this annotation and use it to alter the snapshot test in any way we see fit. In the repository example we use it to change the rendering mode of Paparazzi in one of the previews from the Shrink default we’ve selected for our tests to Normal.</p><h4>Troubleshooting</h4><p>When running the tests to either record ./gradlew screenshot-test:recordPaparazziProdRelease or verify ./gradlew screenshot-test:verifyPaparazziProdRelease we’ll not see the details about the reason of a test failing if there’s something wrong with the test itself:</p><pre>com.google.samples.apps.nowinandroid.screenshottest.PreviewTests &gt; snapshot[NewsFeedKt_NewsFeedLoadingPreview] FAILED<br>    java.lang.IllegalArgumentException at PreviewTests.kt:65<br><br>32 tests completed, 1 failed</pre><p>Luckily, if the test is run as a regular unit test, we’ll be able to see the full stack trace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYpGOh18XqUrz2PnlS8KTQ.png" /></figure><h4>Afterword</h4><p>The proposed solution to automate screenshot testing for Composable previews takes just a couple of hours to integrate into a project, has a maintenance cost close to zero (re-recording the snapshots after any UI changes) but allows you to be sure that any UI change will not cause unexpected changes making the experience of working with Jetpack Compose even better. If you have any ideas or suggestions about ways to improve this — leave a comment!</p><h3>Links</h3><ol><li><a href="https://github.com/rkam88/nowinandroid/">Example project</a></li><li><a href="https://github.com/cashapp/paparazzi">Paparazzi</a></li><li><a href="https://github.com/ronmamo/reflections">Reflections library Github</a></li><li><a href="https://github.com/sergio-sastre/Android-screenshot-testing-playground">Android screenshot testing playground by Sergio Sastre</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6eb0f8fd977" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/automate-screenshot-testing-for-compose-previews-via-reflection-e6eb0f8fd977">Automate screenshot testing for Compose previews via reflection</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[Custom ModalBottomSheet for Material 2 in Compose]]></title>
            <link>https://proandroiddev.com/custom-modalbottomsheet-for-material-2-in-compose-ae50ccc61764?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae50ccc61764</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Tue, 09 May 2023 14:45:05 GMT</pubDate>
            <atom:updated>2024-12-02T15:27:13.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-lcRimEp93ETY-Tx6GyWw.jpeg" /></figure><p><em>Since the publication of this article, </em><em>SwipeableState has been replaced with </em><em>AnchoredDraggableState and the code in the article is currently outdated. Nevertheless, it can still serve as a starting point if you choose to migrate the implementation to </em><em>AnchoredDraggableState.</em></p><p>In this article we’ll go over the implementation of a custom Modal bottom sheet in Compose for Material 2. But first let’s start with a not-so-short intro about why would you want to do that, considering there is already a modal bottom sheet component in the standard library.</p><h4>Why use a custom implementation?</h4><p>Even thought compose has been out for quite some time and with each release we see more and more components being added to the standard library, sometimes their API is far from being ideal. In my opinion, the modal sheet is one of those components. In Material 2, you can show a modal sheet by using ModalBottomSheetLayout:</p><pre>@Composable<br>fun Material2SheetExample() {<br>    val coroutineScope = rememberCoroutineScope()<br>    val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)<br>    ModalBottomSheetLayout(<br>        sheetContent = { /* sheet content... */ },<br>        sheetState = sheetState,<br>    ) {<br>        Button(<br>            onClick = { coroutineScope.launch { sheetState.show() } }<br>        ) { Text(&quot;Show sheet&quot;) }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*ShR7gyeLgAWhfjF-F3J9NQ.png" /></figure><p>And while this definitely works for many cases it has several problems:</p><ol><li>You must use ModalBottomSheetLayout as the root composable of the screen. This can be a problem for complex screens where the root Composable is acting as a container that holds several nested Composable functions, each of which can have their own ViewModel. Being forced to use a specific composable as the root might not always be an option and makes the root composable aware of logic related to it’s children.</li><li>To show the sheet, you must call sheetState.show(). This makes controlling the visibility of the screen harder from the ViewModel as you’d have to rely on LaunchedEffect or similar methods to change the visibility of the sheet based on the state of the ViewModel which adds boilerplate code and unnecessarily increased complexity.</li></ol><h4>A better API in Material 3</h4><p>It would be a lot nicer to have an API, similar to AlertDialog, where you can just use a boolean in the state to control the visibility of the dialog or, in our case, a bottom sheet:</p><pre>@Composable<br>fun AlertDialogExample() {<br>    var showDialog by remember { mutableStateOf(false) }<br>    Button(<br>        onClick = { showDialog = true }<br>    ) { Text(&quot;Show sheet&quot;) }<br>    if (showDialog) {<br>        AlertDialog(...)<br>    }<br>}</pre><p>The AlertDialog composable function can be called from anywhere, it’ll render correctly by showing a scrim that occupies the whole screen and changing it’s visibility based on state is also very easy. In fact, this is the exact approach that was used for the Material 3 version of ModalBottomSheet:</p><pre>@Composable<br>fun Material3SheetExample() {<br>    var showSheet by remember { mutableStateOf(false) }<br>    Button(<br>        onClick = { showSheet = true }<br>    ) { Text(&quot;Show sheet&quot;) }<br>    if (showSheet) {<br>        ModalBottomSheet( // androidx.compose.material3.ModalBottomSheet<br>            onDismissRequest = { showSheet = false },<br>        ) {<br>            // sheet content...<br>        }<br>    }<br>}</pre><p>The sad news is that, as mentioned earlier, this is a Material 3 component, and that might not be an option if your app uses Material 2. Also, at the moment of writing this article ModalBottomSheet is not available in the stable version of the library (but it’s included in the 1.1.0-rc01 version).</p><p>That said, Jetpack Compose does offer a lot of flexibility and a rich public API which makes creating a custom ModalBottomSheet not that complicated, so let’s jump straight into the implementation details of our custom sheet!</p><h3>Building a custom modal sheet</h3><p>We want our sheet to have a similar API to the standard one from Material 3 to allow us an easier migration in the future and we’ll start by defining the 3 possible states that our sheet can have:</p><pre>enum class SheetPosition { HIDDEN, PARTIALLY_EXPANDED, EXPANDED }</pre><p>To control the gestures used to move and dismiss the sheet we’ll use Modifier.swipeable, but before going into any details about how it works, let’s first create the state for our sheet. Besides storing the SwipeableState, that we’ll use for Modifier.swipable, we also need to store a boolean to control if we’re showing the partially expanded state:</p><pre>class SheetState(<br>    val skipPartiallyExpanded: Boolean,<br>    initialPosition: SheetPosition = SheetPosition.HIDDEN,<br>    confirmPositionChange: (SheetPosition) -&gt; Boolean = { true },<br>) {<br>    val swipeableState: SwipeableState&lt;SheetPosition&gt; = SwipeableState(<br>        initialValue = initialPosition,<br>        confirmStateChange = confirmPositionChange,<br>    )<br>}</pre><blockquote>Note that the initial position is HIDDEN, the reason for this is that we want to manually change the state to either PARTIALLY_EXPANDED or EXPANDED after adding the sheet to the screen so that it appears with an animation.</blockquote><p>Since we want the state of the sheet to persist across configuration changes, let’s also create a function to init and remember the state. For this, we’ll use rememberSaveable. Note that according to the <a href="https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md">Compose API guidelines</a>, we’ll add the remember prefix to the function name:</p><pre>@Composable<br>fun rememberSheetState(<br>    skipPartiallyExpanded: Boolean = false,<br>    confirmPositionChange: (SheetPosition) -&gt; Boolean = { true },<br>): SheetState {<br>    return rememberSaveable(<br>        skipPartiallyExpanded, confirmPositionChange,<br>        saver = ...<br>    ) {<br>        SheetState(<br>            skipPartiallyExpanded = skipPartiallyExpanded,<br>            initialPosition = SheetPosition.HIDDEN,<br>            confirmPositionChange = confirmPositionChange,<br>        )<br>    }<br>}</pre><p>Since SheetState is a custom class, we’ll need to provide a Saver instance to be able to save and restore the state across recompositions:</p><pre>class SheetState(...) {<br>    companion object {<br>        fun Saver(<br>            skipPartiallyExpanded: Boolean,<br>            confirmPositionChange: (SheetPosition) -&gt; Boolean,<br>        ) = Saver&lt;SheetState, SheetPosition&gt;(<br>            save = { ... },<br>            restore = { savedValue -&gt; ... }<br>        )<br>    }<br>}</pre><p>For the implementation of Saver&lt;Original, Saveable : Any&gt;, we need to specify the Original object that we’ll save and restore using the save and restore functions (in our case SheetState) and the actual data that we’ll be saving - by default, this can be anything that can be stored in a Bundle and we’ll use the current position of the sheet as this is the only parameter of the state that the user can change.</p><p>For the save function, we’ll just take the current value from SwipeableState:</p><pre>save = { sheetState: SheetState -&gt; sheetState.swipeableState.currentValue }</pre><p>In restore, we’ll receive the saved SheetPosition and create a new instance of SheetState:</p><pre>restore = { savedValue: SheetPosition -&gt;<br>    SheetState(<br>        skipPartiallyExpanded = skipPartiallyExpanded,<br>        initialPosition = savedValue,<br>        confirmPositionChange = confirmPositionChange<br>    )<br>}</pre><h4>Making the sheet swipeable</h4><p>If we wanted to always show the sheet expanded and occupying the full screen, adding the swipeable Modifier would be a very straightforward task and an example implementation was already shown in an <a href="https://proandroiddev.com/how-to-master-swipeable-and-nestedscroll-modifiers-in-compose-bb0635d6a760">article from Angelo Marchesin</a> along with a great explanation about how it works.</p><p>In short, we need to provide a map of anchors to swipeable, that’ll define the height of the sheet for any given state and use Modifier.offset to change the position of the content based on the value from SwipeableState. The main issue, is for the anchor values calculation we need to know the total height available and the height of the sheet itself.</p><p>For the total height, BoxWithConstraints can be used to get the height with BoxWithContsraintsScope.constraints.maxHeight, and for the height of the sheet itself, we can use the onPlaced Modifier to find out the height of the sheet’s content after it’s been placed. We’ll use a helper state variable sheetHeightPx, initially set to UNKNOWN (a constant with a value of -1) and only add the swipeable and offset modifiers after we find out the real size:</p><pre>BoxWithConstraints(<br>    contentAlignment = Alignment.BottomCenter,<br>    modifier = Modifier.fillMaxSize()<br>) {<br>    var sheetHeightPx by remember(sheetState) { mutableStateOf(UNKNOWN) }<br>    val anchors: Map&lt;Float, SheetPosition&gt; by remember(...) { ... }<br><br>    Surface(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .onPlaced { sheetHeightPx = it.size.height }<br>            .let {<br>                if (sheetHeightPx == UNKNOWN) {<br>                    it<br>                } else {<br>                    it.swipeable(<br>                           state = sheetState.swipeableState,<br>                           anchors = anchors,<br>                           orientation = Orientation.Vertical<br>                        )<br>                       .offset {<br>                           IntOffset(<br>                               x = 0,<br>                               y = sheetState.swipeableState.offset.value<br>                                   .toInt()<br>                                   .coerceIn(0, sheetHeightPx)<br>                            )<br>                        }<br>                }<br>            }<br>    ) {<br>        // sheet content goes here<br>    }<br>}</pre><p>The anchors for swipeableState will be calculated based on the total height constaints.maxHeight, sheetHeightPx and wether or not we want (and can) show the partially expanded state:</p><pre>val anchors: Map&lt;Float, SheetPosition&gt; by remember(<br>    sheetHeightPx,<br>    constraints.maxHeight,<br>    sheetState.skipPartiallyExpanded,<br>) {<br>    mutableStateOf(<br>        if (sheetHeightPx == UNKNOWN) {<br>            emptyMap()<br>        } else {<br>            buildMap {<br>                put(0f, SheetPosition.EXPANDED)<br>                if (constraints.maxHeight / 2 &lt; sheetHeightPx &amp;&amp; sheetState.skipPartiallyExpanded.not()) {<br>                    put((sheetHeightPx - constraints.maxHeight / 2).toFloat(), SheetPosition.PARTIALLY_EXPANDED)<br>                }<br>                put(sheetHeightPx.toFloat(), SheetPosition.HIDDEN)<br>            }<br>        }<br>    )<br>}</pre><p>To trigger the animation we can use LaunchedEffect and animate to either PARTIALLY_EXPANDED or to the EXPANDED state once we know the height of the sheet. We’ll animate only if the current position is HIDDEN to avoid changing the sheet’s position after a configuration change.</p><pre>// Show the sheet with animation once we know it&#39;s size<br>LaunchedEffect(sheetHeightPx) {<br>  if (sheetHeightPx != UNKNOWN &amp;&amp; sheetState.swipeableState.currentValue == SheetPosition.HIDDEN) {<br>        val target = if (anchors.containsValue(SheetPosition.PARTIALLY_EXPANDED)) {<br>            SheetPosition.PARTIALLY_EXPANDED<br>        } else {<br>            SheetPosition.EXPANDED<br>        }<br>        sheetState.swipeableState.animateTo(target)<br>    }<br>}</pre><p>The last piece of work with swipeable is to allow the user to dismiss the sheet when swiping down. Because the initial state of our sheet was HIDDEN, we’ll ignore that state for the first time, but invoke onDismissRequest() afterwards so that the parent can react to it accordingly.</p><pre>@Composable<br>fun ModalBottomSheet(<br>    onDismissRequest: () -&gt; Unit,<br>    ...<br>) {<br>    ...<br><br>    // Prevent the sheet from being dismissed during the initial animation when the state is HIDDEN<br>    var wasSheetShown by remember(sheetState) { mutableStateOf(false) }<br>    LaunchedEffect(sheetState.swipeableState.currentValue) {<br>        when (sheetState.swipeableState.currentValue) {<br>            SheetPosition.PARTIALLY_EXPANDED -&gt; wasSheetShown = true<br>            SheetPosition.EXPANDED -&gt; wasSheetShown = true<br>            SheetPosition.HIDDEN -&gt; if (wasSheetShown) onDismissRequest()<br>        }<br>    }<br>}</pre><p>So far we’ve build our sheet and made it swipeable, but there’s a few things missing: it has no scrim, doesn’t support nested scrolling and can’t be called from anywhere and still take up all the availalbe screen space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*7Jb1ArFcVszAAx3o0sJHVQ.gif" /></figure><h4>Making the sheet a Popup</h4><p>We wanted to be able to call the sheet from any Composable so that it occupies the whole screen. This can be easily achieved by using the same approach as in the Material 3 implementation by wrapping our code with a Popup composable:</p><pre>@Composable<br>fun ModalBottomSheet(<br>    onDismissRequest: () -&gt; Unit,<br>    sheetState: SheetState = rememberSheetState(),<br>    content: @Composable () -&gt; Unit,<br>) {<br>    val coroutineScope = rememberCoroutineScope()<br><br>    val closeSheet: () -&gt; Unit = {<br>        coroutineScope.launch { sheetState.swipeableState.animateTo(SheetPosition.HIDDEN) }<br>    }<br><br>    Popup(<br>        onDismissRequest = closeSheet,<br>        properties = PopupProperties(focusable = true),<br>    ) {<br>        BoxWithConstraints(...) {<br>           Surface(...) {<br>                content()<br>            }<br>        }<br>    }<br>}</pre><p>We use closeSheet to hide the sheet with an animation when the user attempts to dismiss the popup. focusable is set to true so that our Popup can receive and handle IME events and key presses — for example when pressing the back key, which would cause the closeSheet lambda to be called.</p><h4>Adding a background</h4><p>For the scrim, we can use a custom Composable added in the BoxWithConstraints that holds the Surface with the sheet’s content.</p><pre>Popup(onDismissRequest = closeSheet, ...) {<br>    BoxWithConstraints(...) {<br>        ScrimBackground(<br>            swipeableState = sheetState.swipeableState,<br>            onClick = closeSheet<br>        )<br><br>        Surface(...) {<br>            content()<br>        }<br>    }<br>}</pre><p>We can use SwipeableState to control it’s visibility and invoke the same closeSheet lambda used in the Popup to close the sheet if the user taps on the scrim:</p><pre>@Composable<br>private fun ScrimBackground(<br>    swipeableState: SwipeableState&lt;SheetPosition&gt;,<br>    onClick: () -&gt; Unit,<br>) {<br>    val showScrim by remember {<br>        derivedStateOf { swipeableState.targetValue != SheetPosition.HIDDEN }<br>    }<br>    val scrimAlpha by animateFloatAsState(targetValue = if (showScrim) SCRIM_ALPHA else 0f)<br>    Canvas(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .pointerInput(Unit) { detectTapGestures { onClick() } }<br>    ) {<br>        drawRect(color = Color.Black, alpha = scrimAlpha)<br>    }<br>}</pre><p>Note that we’re using pointerInput instead of clickable to avoid playing the ripple animation when the user taps on the scrim.</p><h4>Final touches</h4><p>After adding a scrim, we can add support for nested scroll with NestedScrollConnection in a way similar to the implementation in <a href="https://proandroiddev.com/how-to-master-swipeable-and-nestedscroll-modifiers-in-compose-bb0635d6a760">Angelo’s article</a>. Also we want to expose some additional parameters to the caller so that the shape and colors of the sheet can be customised:</p><pre>@Composable<br>fun ModalBottomSheet(<br>    onDismissRequest: () -&gt; Unit,<br>    sheetState: SheetState = rememberSheetState(),<br>    shape: Shape = RectangleShape,<br>    color: Color = MaterialTheme.colors.surface,<br>    contentColor: Color = contentColorFor(color),<br>    border: BorderStroke? = null,<br>    content: @Composable () -&gt; Unit,<br>) {<br>    Popup(...) {<br>        BoxWithConstraints(...) {<br>            ScrimBackground(...)<br>            Surface(<br>                shape = shape,<br>                color = color,<br>                contentColor = contentColor,<br>                border = border,<br>                modifier = ...<br>            ) {<br>                content()<br>            }<br>        }<br>    }<br>}</pre><p>After applying the final changes, you can see the <a href="https://gist.github.com/rkam88/a0843ccbf3741cee85eff8354561b8f9">full code here</a>, and this is what the final result looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Gd0MtXFEPYnQoQ00g6oFiw.gif" /></figure><h4>Links</h4><ol><li><a href="https://gist.github.com/rkam88/a0843ccbf3741cee85eff8354561b8f9">Full custom ModalBottomSheet implementation with example</a></li><li><a href="https://proandroiddev.com/how-to-master-swipeable-and-nestedscroll-modifiers-in-compose-bb0635d6a760">How to master Swipeable and NestedScroll modifiers in Jetpack Compose by Angelo Marchesin</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae50ccc61764" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/custom-modalbottomsheet-for-material-2-in-compose-ae50ccc61764">Custom ModalBottomSheet for Material 2 in Compose</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[Performance Issues with Jetpack Compose & LiveData as a state holder]]></title>
            <link>https://medium.com/@rkam88/performance-issues-with-jetpack-compose-livedata-as-a-state-holder-557bbac030c9?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/557bbac030c9</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 12:18:37 GMT</pubDate>
            <atom:updated>2023-03-29T12:18:37.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdSYG7MnTBuO5RMVgfly0Q.jpeg" /></figure><p>In recent years, Android developers have increasingly turned to Jetpack Compose as a powerful toolkit for designing modern, declarative UIs. One of its notable features is the ability to seamlessly <a href="https://developer.android.com/jetpack/compose/state#use-other-types-of-state-in-jetpack-compose">integrate with different observables</a>, allowing for easy state management and automatic updates. However, as with any new technology, certain challenges can arise when integrating it with your current codebase. In this article, we’ll explore a performance issue that can arise when using LiveData as a state holder for Jetpack Compose and provide solutions to address it.</p><p>Before we dive into the issue, let’s provide a bit of background on Jetpack Compose and LiveData. Jetpack Compose is a modern UI toolkit for Android development that allows developers to build UIs declaratively using Kotlin code. It offers a number of benefits, including a simpler and more intuitive UI design process and better support for animations and gestures.</p><p>LiveData, on the other hand, is a lifecycle-aware observable data holder that is part of the Jetpack library. It allows developers to easily manage app data and automatically update the UI when the data changes. LiveData is particularly useful when working with Jetpack Compose because it seamlessly integrates with the toolkit and allows developers to manage UI state without having to write additional code.</p><p>While Jetpack Compose and LiveData seem to work great together, I’ve found that unexpected performance issues can occur under certain circumstances, for example when using LiveData to hold and update the state of a Slider.</p><p>Consider the following code snippet:</p><pre>private val sliderState = MutableLiveData&lt;Float&gt;(0f)<br><br>@Composable<br>fun SliderExample() {<br>    val sliderValue by sliderState.observeAsState(0f)<br>    Slider(<br>        value = sliderValue,<br>        onValueChange = { sliderState.postValue(it) },<br>    )<br>}</pre><p>If you run this code and try to move the slider, you’ll notice that there is a significant lag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pqqP5Nc6iSQsZbr4U_q0aA.gif" /></figure><p>You might be aware that Compose can have <a href="https://medium.com/proandroiddev/jetpack-compose-in-production-code-first-impressions-dd8fabd4a3c8">performance issues in debug builds without R8</a>. but trying to run the code above in a release build will have the exact same effect!</p><p>The reason behind the laggy behaviour is that LiveData’s postValue method can be called from any thread, including background threads. When you call postValue, it schedules the update of LiveData&#39;s value to be executed on the main thread. As a result, the update is not instantaneous, and there might be a delay before the LiveData observers are notified of the change. In essence, using LiveData’s postValue method is an async operation, which is considered an anti-pattern for Jetpack Compose.</p><p>Another example of performance issues, caused by updating the state asynchronously was described in a <a href="https://medium.com/androiddevelopers/effective-state-management-for-textfield-in-compose-d6e5b070fbe5">great article by Alejandra Stamato</a> — in the article, after receiving a callback from a TextField, the ViewModel calls an API to verify the user input and updates the state only after receiving the result. This can be solved by avoiding delays when updating the state synchronously and immediately after receiving the callback.</p><p>To address this Slider issue, you can use LiveData’s setValue method instead of postValue. Unlike postValue, setValue must be called from the main thread, which means that LiveData&#39;s value is updated immediately, and all active observers are notified of the change right away. This can significantly improve the performance of your app in general and eliminate the lag when using a Slider.</p><p>However, it’s worth noting that while setValue can be used to address the performance issues with LiveData, it&#39;s not always the best option. You’ll need to be extra careful and ensure that setValue is being called from the main thread or you risk getting a IllegalStateException at runtime, which would cause you app to crash.</p><p>Considering that both postValue and setValue methods have significant drawbacks, you might want to consider a third alternative and migrate away from LiveData entirely and start using Kotlin’s native hot observable StateFlow when working with Jetpack Compose:</p><pre>private val sliderState = MutableStateFlow&lt;Float&gt;(0f)<br><br>@Composable<br>fun SliderExample() {<br>    val sliderValue by sliderState.collectAsStateWithLifecycle()<br>    Slider(<br>        value = sliderValue,<br>        onValueChange = { sliderState.value = it },<br>    )<br>}</pre><blockquote>Note that the state is being collected with collectAsStateWithLifeCycle() operator instead of just collectAsState(). This new API is a safer way to collect flows and it’s available in androidx.lifecycle:lifecycle-runtime-compose version 2.6.0 or higher. It’s advantages where covered in great detail in this <a href="https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3">blog post by Manuel Vivo</a>.</blockquote><p>Personally I think that migrating to StateFlow if your using LiveData is the best alternative as it allows us to avoid performance issues and doesn’t bring the risk of getting a crash at runtime, which helps you ensure that your app performs well and provides a great user experience.</p><p><strong>Links:</strong></p><ol><li><a href="https://medium.com/androiddevelopers/effective-state-management-for-textfield-in-compose-d6e5b070fbe5">Effective state management for TextField in Compose — Alejandra Stamato</a></li><li><a href="https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3">Consuming flows safely in Jetpack Compose — Manuel Vivo</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557bbac030c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to mock Retrofit API calls (or any other interface)]]></title>
            <link>https://proandroiddev.com/how-to-mock-retrofit-api-calls-or-any-other-interface-53161eee6789?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/53161eee6789</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 16:57:16 GMT</pubDate>
            <atom:updated>2025-10-18T11:05:47.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_X37OYiHCZumEci49K0LA.jpeg" /></figure><p>In Android development, it’s quite common that we need to start working on a feature before the backend is ready. While we’re waiting for it to be ready, there are several ways to mock it, like using <a href="https://learning.postman.com/docs/designing-and-developing-your-api/mocking-data/mocking-with-examples/">Postman</a>, <a href="https://proandroiddev.com/mocking-a-server-with-firebase-3b4376ce3596">Firebase</a> or <a href="https://www.thinktecture.com/tools/debugging-proxies-mocking-manipulating-api-charles-in-action/">Charles Proxy</a>, but all these methods require some sort of initial setup that often needs to be performed on each device.</p><p>An alternative approach, that uses an OkHttp Interceptor, was described by Wahib Ul Haq in this <a href="https://medium.com/ki-labs-engineering/an-easy-way-to-mock-an-api-response-using-retrofit-okhttp-and-interceptor-7968e1f0d050">article</a>. Even though the described method is a completely valid solution, mocking several methods at the same time and accessing the parameters of those methods can get complicated pretty fast. Also, using the URL string address to identify the invoked method and returning a JSON created from a string can easily lead to mistakes if you plan to keep the mocks in the app for debug builds — a change in the name of the method or its return type or implementation might go unnoticed until the method gets called.</p><p>So, based on known solutions and their disadvantages, let’s create a list of requirements that we’d like to see in an interface mock:</p><ul><li>easy and compile-time safe to add, modify and remove mocks;</li><li>no tedious setup procedures for different devices. We should be able to easily enable and disable all mocks (or some of them if needed);</li><li>the ability to add a delay for suspend functions before returning a result. API calls are never instant and you probably want to see that a loader is being displayed correctly, animations play as they should, etc.</li></ul><h3>The first step: delegation</h3><p>The first solution that comes to mind, when you want to “intercept” some method calls, while calling the real implementation for the rest is to just use a delegate. Luckily for us, this is trivial in Kotlin. Let’s say that we have some interface and an implementation:</p><pre>interface SomeApi {<br>    suspend fun foo(): String<br>    suspend fun bar(): String<br>    suspend fun baz(): String<br>}<br><br>class SomeApiImpl : SomeApi {<br>    override suspend fun foo() = &quot;Actual foo&quot;<br>    override suspend fun bar() = &quot;Actual bar&quot;<br>    override suspend fun baz() = &quot;Actual baz&quot;<br>}</pre><p>Now, we can easily delegate one of the methods:</p><pre>class SomeApiMock(<br>    private val actual: SomeApi,<br>) : SomeApi by actual {<br>   override suspend fun foo() = &quot;Mocked foo&quot;<br>}</pre><p>And we can wrap our actual implementation with the mock:</p><pre>fun wrapSomeApi(actual: SomeApi): SomeApi {<br>    // we only want to mock calls in debug builds!!<br>    return if (BuildConfig.DEBUG) SomeApiMock(actual) else actual<br>}</pre><p>This lets us meet the first requirement. Adding or modifying mocks is super-easy and safe: if the methods signature or its parameter changes and we forget to update the mocks we will get an error at compile time.</p><p>What about the other two points? We could add a variable, like <strong><em>isFooMockEnabled</em></strong>, to control the mock or add a global variable to control all mocks, or do both. For delays, we could just add the delay in the mocked method too. It’s not complicated at all, but we’d need to do the same thing for each method that we mock and that would be boilerplate! Global mock control and delays can and should be controlled from a single place and Java’s dynamic proxy comes to the rescue here.</p><h3>Controlling mock behaviour with Java Dynamic Proxy</h3><p>A Proxy can be created by calling the <strong><em>Proxy.newProxyInstance(…)</em></strong> method and providing at least one interface for it as well as an InvocationHandler:</p><pre>fun &lt;T : Any&gt; create(<br>    clazz: Class&lt;T&gt;,<br>    actual: T,<br>    mock: T,<br>    controller: MockProxyController,<br>): T {<br>    return Proxy.newProxyInstance(<br>        clazz.classLoader,<br>        arrayOf(clazz),<br>        MockProxyInvocationHandler(actual, mock, controller)<br>    ) as T<br>}</pre><p>The proxy will dispatch all method invocations to the provided InvocationHandler, which has one method — invoke:</p><pre>internal class MockProxyInvocationHandler&lt;T : Any&gt;(<br>    private val actual: T,<br>    private val mock: T,<br>    private val controller: MockProxyController,<br>) : InvocationHandler {<br><br>    override fun invoke(proxy: Any, method: Method, args: Array&lt;out Any&gt;?): Any? {<br>        // handle method invocation here!<br>    }<br><br>}</pre><p>An important thing to notice is that Java’s Dynamic Proxy relies on reflection, which has some overhead, but since we’re only going to use it in debug builds, it should not be a problem.</p><p>Also, you might have noticed MockProxyController in the code above. It’s the interface that we’ll use to control the behaviour of our mocks.</p><pre>interface MockProxyController {<br>    val areMocksEnabled: Boolean<br>    val suspendFunctionsDelay: Long<br>}</pre><p>Note that we can use the MockProxyController instance to alter the behaviour of our mocks at runtime — just add a simple debug menu with a couple of toggle buttons somewhere.</p><p>Another useful thing that we might make use of is an exception, that a mocked function can throw at any time if it wants the invocation handler to repeat the method invocation, but use the actual implementation this time:</p><pre>object MockDisabledException : Exception()</pre><h3>Implementing MockProxyInvocationHandler</h3><p>First, we need to choose whether to call the actual implementation or the mock. A handy way to do that is by adding the private field <strong>targetObject</strong> and using our MockProxyController to return one of them:</p><pre>private val targetObject: T<br>    get() = if (controller.areMocksEnabled) mock else actual</pre><p>To call a method, we can use the input parameters of the function and reflection:</p><pre>override fun invoke(proxy: Any, method: Method, args: Array&lt;out Any&gt;?): Any? {<br>        val safeArgs = args ?: emptyArray()<br>        return method.invoke(targetObject, *safeArgs)<br>    }</pre><p>This will seem to work, but there are some problems:</p><ul><li>If the method that is invoked using reflection throws an exception, it’ll be wrapped in an InvocationTargetException, so we need to intercept it and unwrap it before re-throwing it.</li><li>No delay for suspend functions yet. We need a way to find out if the invoked method is a suspending one and delay the return somehow.</li></ul><p>First, let’s split our implementation into two parts: one for regular functions and a second implementation for suspending functions.</p><p>Due to the way suspend functions are implemented, they get an extra Continuation parameter added at the end during compilation. We can check for this parameter to determine if the function is a suspending one or not:</p><pre>override fun invoke(proxy: Any, method: Method, args: Array&lt;out Any&gt;?): Any? {<br>    val safeArgs = args ?: emptyArray()<br>    val continuation = args?.firstNotNullOfOrNull { it as? Continuation&lt;Any?&gt; }<br><br>    return if (continuation == null) {<br>        invokeMethod(method, targetObject, safeArgs)<br>    } else {<br>        invokeSuspendingFunction(method, targetObject, safeArgs, continuation)<br>        COROUTINE_SUSPENDED<br>    }<br>}<br><br>private fun invokeMethod(...): Any? { ... }<br>private fun invokeSuspendingFunction(...): Unit { ... }</pre><p>Note that for the suspending function, we don’t return the result immediately. Instead, we return the constant <strong><em>COROUTINE_SUSPEND</em></strong>, which is used internally in coroutines to let the caller know that the function is suspended and will later resume using the Continuation object. To get a better understanding of how coroutines work internally, please check out <a href="https://kt.academy/article/cc-under-the-hood">Kt.Academy</a> — it has a very detailed example. For a general overview of coroutines — please refer to my previous <a href="https://medium.com/r?url=https%3A%2F%2Fproandroiddev.com%2Fkotlin-coroutines-in-android-summary-1ed3048f11c3">article</a>.</p><p>Now, let’s see how the <strong><em>invokeMethod</em></strong> is implemented:</p><pre>private fun invokeMethod(method: Method, obj: Any, safeArgs: Array&lt;out Any&gt;): Any? {<br>    return try {<br>        method.invoke(obj, *safeArgs)<br>    } catch (exception: Exception) {<br>        when (val actualException = exception.unwrap()) {<br>            is MockDisabledException -&gt; invokeMethod(method, actual, safeArgs)<br>            else -&gt; throw actualException<br>        }<br>    }<br>}<br><br>private fun Throwable.unwrap(): Throwable {<br>    return (this as? InvocationTargetException)?.cause ?: this<br>}</pre><p>First, we try to call the method for the passed object (that we got from targetObject). If we get any exception, we try to unwrap if from the InvocationTargetException and then if it’s the MockDisabledException we talked about earlier — call the same method again, but use the actual instance this time. If it’s some other exception, then we can just re-throw it and let the caller handle it.</p><p>The <strong><em>invokeSuspendingFunction</em></strong> implementation is similar, but with a few nuances caused by coroutines:</p><pre>private fun invokeSuspendingFunction(<br>        method: Method, obj: Any, safeArgs: Array&lt;out Any&gt;, continuation: Continuation&lt;Any?&gt;<br>    ) {<br>        // Get the delay duration that we&#39;ll use (only if the target is the mock implementation)<br>        val delayDuration = controller.suspendFunctionsDelay.takeIf { obj == mock } ?: 0L<br><br>        CoroutineScope(continuation.context).launch {<br>            try {<br>                coroutineScope {<br>                    launch {<br>                        val result = method.invoke(obj, *safeArgs)<br>                        if (result != COROUTINE_SUSPENDED) {<br>                            // the invoked function might return COROUTINE_SUSPEND,<br>                            // but since we already returned it from the InvocationHandler.invoke method<br>                            // we need to ignore it this time!!!<br>                            continuation.resumeWithAfterDelay(Result.success(result), delayDuration)<br>                        }<br>                    }<br>                }<br>            } catch (exception: Exception) {<br>                when (val actualException = exception.unwrap()) {<br>                    is MockDisabledException -&gt; invokeSuspendingFunction(method, actual, safeArgs, continuation)<br>                    is CancellationException -&gt; continuation.resumeWith(Result.failure(actualException))<br>                    else -&gt; continuation.resumeWithAfterDelay(Result.failure(actualException), delayDuration)<br>                }<br>            }<br>        }<br>    }<br><br>    // Delay before resuming the coroutine execution<br>    private suspend fun Continuation&lt;Any?&gt;.resumeWithAfterDelay(result: Result&lt;Any?&gt;, timeMillis: Long) {<br>        delay(timeMillis)<br>        resumeWith(result)<br>    }</pre><p>The details about the delay are added as comments in the code above, and exception handling is similar to the code in <strong><em>invokeMethod</em></strong>. Note that for a positive result the delay is used only after we actually get the result: if a mocked method throws a MockDisabledException, we’d want to call the actual implementation straight away. Also, calling delay for a cancelled coroutine is not possible and makes no sense, so we just pass the CancellationException to the caller like a regular coroutine would.</p><p>The coroutine creation process might seem a bit tricky, but it’s actually not that hard:</p><p><strong><em>We should follow structured concurrency and cancel our coroutine if it’s scope is cancelled:</em></strong> for this, we use the context of the continuation to create a CoroutineScope.</p><p><strong><em>We need to intercept all exceptions to unwrap them and allow for flow control using MockDisabledException:</em></strong> the method that we call might have a coroutine inside and if an exception is thrown there — it’ll be propagated up the job hierarchy causing us to miss it! To catch these exceptions — we can use <strong><em>coroutineScope</em></strong>. Although it is generally used for parallel decomposition of work, it has the property of catching all exceptions from its child coroutines and actually re-throwing them instead of propagating them up, which is exactly what we need — catching the exception in the try-catch statement while still remaining inside the coroutine will allow us apply the delay before re-throwing it to the original caller.</p><p><em>Note: in general, using exceptions for flow control is an anti-pattern, but it seems to be an ok solution for this case. Please share any thoughts about this or other possible solutions in the comments.</em></p><p>After adding the functions to handle regular and suspending functions to our InvocationHandler, we’re ready to use our MockProxy. You can find the full code <a href="https://gist.github.com/rkam88/0dff26cbcfcb61413e44e41bf28f3d82">here</a>.</p><p>After copying into your project, all you need to do is implement MockProxyController (or use the default one — DefaultMockProxyController), create a mock implementation for the api you want to mock and create a proxy with it:</p><pre>class SomeApiMockController : MockProxyController {<br>    override val areMocksEnabled: Boolean<br>        get() = mockFoo || mockBaz<br>    override var suspendFunctionsDelay: Long = 3000L<br>    var mockFoo = true<br>    var mockBaz = false<br>}<br><br>class SomeApiMock(<br>    private val actual: SomeApi,<br>    private val controller: SomeApiMockController,<br>) : SomeApi by actual {<br><br>    private inline fun &lt;T&gt; getResult(<br>        isMockEnabled: Boolean = true,<br>        method: () -&gt; T,<br>    ): T {<br>        if (isMockEnabled) return method() else throw MockDisabledException<br>    }<br><br>    override suspend fun foo() = getResult(controller.mockFoo) { &quot;Mocked foo&quot; }<br>    override suspend fun baz() = getResult(controller.mockBaz) { &quot;Mocked baz&quot; }<br>}<br><br>suspend fun example() {<br>    val actual = SomeApiImpl()<br>    val controller = SomeApiMockController()<br>    val mock = SomeApiMock(actual, controller)<br>    val proxy = MockProxy.create(actual, mock, controller)<br><br>    proxy.foo() // returns &quot;Mocked foo&quot;<br>    proxy.bar() // returns &quot;Actual bar&quot;<br>    proxy.baz() // returns &quot;Actual baz&quot;, because the mock is disabled and MockDisabledException is thrown<br>}</pre><h3>A few things to remember</h3><p>While the provided MockProxy has all the advantages that we need and it lets us create and change mocks very fast, the use of reflection does add some overhead and it should be used only in debug builds to avoid impacting performance. Another important thing is that no OkHttp Interceptors are called for the mocked methods because the invocation never actually reaches Retrofit. This will probably be fine for most cases, but for some others — you might need to use one of the other options described in the intro.</p><p><em>P.s. A special thank you to </em><a href="https://t.me/eimamedov"><em>Mamedov Eldar</em></a><em>, for helping me test MockProxy and finding a quite nasty bug in the process.</em></p><h3>Links</h3><ol><li><a href="https://gist.github.com/roman-kamyshnikov/a13a8894017c5c54610b524b0d4a0c47">Full MockProxy code with example</a></li><li><a href="https://kt.academy/article/cc-under-the-hood">Kotlin coroutines under the hood (Kt.Academy)</a></li><li><a href="https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3">Kotlin coroutines in Android summary</a></li><li><a href="https://medium.com/ki-labs-engineering/an-easy-way-to-mock-an-api-response-using-retrofit-okhttp-and-interceptor-7968e1f0d050">Mocking Retrofit API calls with Interceptor</a></li><li><a href="https://phase2online.com/2021/05/14/creating-dynamic-proxies-with-kotlin-coroutines/">Creating Java Dynamic Proxies with Kotlin coroutines</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53161eee6789" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/how-to-mock-retrofit-api-calls-or-any-other-interface-53161eee6789">How to mock Retrofit API calls (or any other interface)</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 Flows in Android summary]]></title>
            <link>https://proandroiddev.com/kotlin-flows-in-android-summary-8e092040fb3a?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e092040fb3a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 17:19:30 GMT</pubDate>
            <atom:updated>2021-12-23T16:02:31.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ab9qskEuQtdigd7SYcx5CA.jpeg" /></figure><p>Just like my previous <a href="https://medium.com/@rkam88/kotlin-coroutines-in-android-summary-1ed3048f11c3">article</a> about coroutines, this is an attempt to group most of the information you’ll need to use Kotlin flows in Android and provide you with links you can use to get more in-depth details on any of the covered topics.</p><p>Flow is the Kotlin type that can be used to model streams of data. Just like LiveData and RxJava streams, Flow lets you implement the observer pattern: a software design pattern that consists of an object (a.k.a. observable, producer, source, emitter) that maintains a list of its dependents, called observers (subscribers, collectors, receivers, etc.), and notifies them automatically of any state changes. This terminology is used interchangeably throughout this article depending on the context, but those terms always refer to the same two entities.</p><p>Observables can be either hot or cold. Hot observables send or emit data even if no one is watching them and cold observables emit data only if they have an active observer. By default, Kotlin flows are cold.</p><h3>Creating flows</h3><p>The standard library provides you with several ways to create a flow, the easiest way is to use the <strong><em>flow</em></strong> operator:</p><pre>fun numbersFlow(): Flow&lt;Int&gt; = flow {<br>    // code inside flow can suspend!<br>    for (i in 1..3) { <br>        delay(100)<br>        emit(i)<br>    }<br>} // the function numbersFlow() itself does not suspend</pre><p>There are other ways to create a Flow, including the <strong><em>flowOf()</em></strong> function, and the extension <strong><em>asFlow()</em></strong>, which can be used for collections, sequences, ranges, values or functional types:</p><pre>flowOf(1,2,3)<br>listOf(“A”,“B”,“C”).asFlow()<br>(1..3).asFlow()</pre><h3>Collecting flows</h3><p>Flows are cold, which means that the code inside a flow builder does not execute until a terminal operator is applied to the flow. The most common terminal operator is <strong><em>collect:</em></strong></p><pre>someCoroutineScope.launch {<br>    numbersFlow.collect { value -&gt; print(value) }<br>}</pre><p>Some other terminal operators include:</p><ul><li><strong><em>toCollection(destination: C)</em></strong> collects the flow into the provided MutableCollection. This operator has two convenient wrappers: <strong><em>toList</em></strong> and <strong><em>toSet</em></strong>;</li><li><strong><em>first()</em></strong> and <strong><em>last()</em></strong> return the respective element or NoSuchElementException. There are also variants that take a predicate as an argument or return null instead of throwing an exception;</li><li><strong><em>single()</em></strong> awaits for just one value to be emitted and can throw NoSuchElementException like <strong><em>first()</em></strong> or IllegalStateException if the flow contains more than one element. A <strong><em>singleOrNull()</em></strong> variation also exists;</li><li><strong><em>reduce()</em></strong> and <strong><em>fold()</em></strong> can be used to reduce a flow to a single value.</li></ul><p>An important thing to keep in mind is that all terminal operators are suspending functions and thus must be called from a coroutine. Also, all these operators will suspend the coroutine until the flow is fully collected.</p><p>To prevent the flow collection from suspending the current scope, you can use the <strong><em>launchIn</em></strong> operator:</p><pre>someCoroutineScope.launch {<br>    val job = numbersFlow<br>        .onEach { value -&gt; println(value) }<br>        <strong>.launchIn(scope = this)</strong><br>}</pre><p>The <strong><em>launchIn</em></strong> operator returns a Job that can be used to <strong><em>cancel()</em></strong> the flow collection without canceling the whole coroutine scope. If needed, you can use <strong><em>join()</em></strong> to wait for the job to complete.</p><p>Keep in mind that the operators <strong><em>first</em></strong>, <strong><em>last</em></strong> and <strong><em>toList</em></strong> can be very helpful when writing unit-tests for classes that expose flows.</p><h3>Collecting flows in Android</h3><p>In Android, usually you’ll end up collecting a Flow in the presentation layer of your app, i.e. a Fragment or an Activity. Obviously, when the UI is not on the screen and we don’t need to display the information we’re getting, so we should stop flow collection. There are several lifecycle-aware alternatives you could use to handle this automatically:</p><ul><li>Flow&lt;T&gt;.<strong><em>asLiveData</em></strong>(): LiveData</li><li>Lifecycle.<strong><em>repeatOnLifeCycle</em></strong>(state)</li><li>Flow&lt;T&gt;.<strong><em>flowWithLifecycle</em></strong>(lifecycle, state)</li></ul><p>Using <strong><em>asLiveData</em></strong> might not be the best solution, because it involves combining Flows with another library that’s actually not needed, but is very helpful in the process of migrating from LiveData to Flow.</p><p><strong><em>repeatOnLifeCycle</em></strong> is a suspending function and you need to specify a <strong><em>Lifecycle.State</em></strong> as its input. A new coroutine will be launched each time the lifecycle reaches that state and will automatically be canceled once the lifecycle goes below the specified state:</p><pre>class MyActivity: AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        // ...<br>        lifecycleScope.launch {<br>            repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                viewModel.someFlow().collect {<br>                    // flow is collected during the time<br>                    // we’re in the STARTED state.<br>                }<br>            } <br>            // resumes only when lifecycle is DESTROYED!!!<br>        }<br>    }<br>}</pre><p>Note that the <strong><em>repeatOnLifecycle</em></strong> suspends the coroutine until the lifecycle reaches the DESTROYED state. To collect several flows, you can launch several coroutines:</p><pre>repeatOnLifecycle(Lifecycle.State.STARTED) {<br>    launch { viewModel.someFlow().collect { /* ... */ } }<br>    launch { viewModel.someOtherFlow().collect { /* ... */ } }<br>}</pre><p>If you only need to collect a single flow, <strong><em>flowWithLifecycle</em></strong> can be used:</p><pre>lifecycleScope.launch {<br>    viewModel.someFlow()<br>        .flowWithLifecycle(lifecycle, State.STARTED)<br>        .collect { /* ... */ }<br>}</pre><p>The APIs <strong><em>repeatOnLifeCycle</em></strong> and <strong><em>flowWithLifecycle</em></strong> are the currently recommended approaches and are available in the androidx.lifecycle:lifecycle-runtime-ktx library (version 2.4.0 and above).</p><h3>Intermediate operators</h3><p>The behaviour of a flow can be modified by applying different operators to it, just like with collections and sequences. Operators are not suspending functions: they are immediately applied to an upstream flow (before/above the operator) and return a new, transformed flow, but are executed lazily as each item is emitted into the flow.</p><p>I can’t think of a better way of getting familiar with different operators than playing round with <a href="https://flowmarbles.com/">https://flowmarbles.com</a> (flow’s version of <a href="https://rxmarbles.com/">https://rxmarbles.com</a>). It’s an awesome resource that provides interactive diagrams of the operators you can use on flows. Note that you can move the marbles around and see how they affect the resulting flow.</p><h3><strong>Context</strong></h3><p>Unless special intermediate operators that use multiple flows are used, all emitted values are processed by the operators sequentially from upstream to downstream and then delivered to the terminal operator.</p><p>By default, code in builders, intermediate operators and the collection itself is performed in the coroutine context that invoked the terminal operator. This property of flows is called context preservation.</p><p>This might be ok for fast-running, non-blocking code, but for some long term operations you might want to execute the code in a different Dispatcher, like Default or IO.</p><p>In suspending functions you could use <strong><em>withContext()</em></strong> to change the Dispatcher, but code inside builders is not allowed to emit from a different context (thus breaking context preservation) and attempting to use <strong><em>withContext()</em></strong> will throw a runtime Exception.</p><p>To change the context, you can use the <strong><em>flowOn()</em></strong> operator:</p><pre>fun numbersFlow() = flow { // runs in Dispatchers.Default<br>        for (i in 1..3) {<br>            Thread.sleep(100) // some long-running operation<br>            emit(i)<br>        }<br>    }<br>    .onEach { /* still in Dispatchers.Default */ }<br>    .flowOn(Dispatchers.Default) // changing dispatcher</pre><pre>lifecycleScope.launch(Dispatchers.Main) {<br>    numbersFlow()<br>        .onEach { /* in Dispatchers.Main */ }<br>        .collect { value -&gt;  /* Dispatchers.Main */ }<br>}</pre><p>Collection and emission is now happening concurrently in different coroutines. Remember that the <strong><em>flowOn</em></strong> operator only changes the coroutine context in the builder and operators applied upstream of it.</p><h3><strong>Buffering</strong></h3><p>As stated above — flows execute code in the building block, operator and terminal operator sequentially:</p><pre>flowOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)<br>    .onEach  { print(&quot;1$it &quot;) }<br>    .collect { print(&quot;2$it &quot;) }<br>// prints &quot;1A 2A 1B 2B 1C 2C&quot;</pre><p>As a consequence — the total execution time is going to be the sum of the execution times of all the operators. To prevent waiting for all upstream operators to complete on each emitted value instead of changing the coroutine context with the <strong><em>flowOn()</em></strong>, you can apply the <strong><em>buffer()</em></strong> operator:</p><pre>flowOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)<br>    .onEach  { print(&quot;1$it &quot;) }<br>    .buffer()<br>    .collect {<br>        delay(100)<br>        print(&quot;2$it &quot;)<br>    }<br>// prints &quot;1A 1B 1C 2A 2B 2C &quot;</pre><p>The <strong><em>buffer()</em></strong> operator creates a separate coroutine during execution for the flow it is applied to. This coroutine will be used to execute the code in the producer and upstream operators.</p><p>If the consumer is slower than the producer , the buffer will become full at some point and, by default, will suspend the producer coroutine until the consumer coroutine catches up. This default strategy (<strong><em>BufferOverflow.SUSPEND</em></strong>) can be overridden by passing a different strategy to the operator, for example <strong><em>DROP_OLDEST</em></strong> or <strong><em>DROP_LATEST</em></strong>.</p><p>When a flow represents partial results of the operation or operation status updates, it may not be necessary to process each value, but instead, only the most recent ones. In this case, the <strong><em>conflate</em></strong> operator can be used to skip intermediate values when a collector is too slow to process them. Note that this function is just a shortcut for a buffer with a capacity of 0 and a <strong><em>DROP_OLDEST</em></strong> overflow strategy.</p><p>Another way to speed up processing with a slow collector is to cancel and restart it every time a new value arrives. You can use operators like <strong><em>collectLatest()</em></strong> for this behaviour.</p><pre>someFlow()<br>    .collectLatest { value -&gt; <br>        println(&quot;Collecting $value&quot;)<br>        delay(300) // pretend we are processing it for 300 ms<br>        println(&quot;Done $value&quot;)<br>    }</pre><p>Important note: remember that cancellation in coroutines is cooperative. The code in the <strong><em>collectLatest()</em></strong> block above is able to cancel because <strong>delay<em>()</em></strong> is cancellable.</p><h3>Exceptions</h3><p>Flow collection can complete with an exception if it’s thrown inside the building block or any of the operators. Exceptions can be handled in both imperative and declarative ways:</p><pre>fun numbers() = flow {<br>    repeat(10) { emit(it) }<br>}</pre><pre>try {<br>    numbers().collect {<br>            check(it &lt;= 1) { &quot;Crashed on $it&quot; }<br>            print(&quot;$it;&quot;)<br>        }<br>} catch (e:Exception) { <br>    print(&quot;Exception caught(${e.message})!&quot;)<br>}</pre><pre>// prints &quot;0;1;Exception caught(Crashed on 2)!&quot;</pre><p>Flows must be transparent to exceptions and it is a violation of the exception transparency principle to emit values in a flow builder from inside of a try/catch block. This guarantees that a collector throwing an exception can always catch it using try/catch as in the previous example.</p><p>If we define the numbers flow as:</p><pre>fun <strong>doNotDoThis()</strong> = flow {<br>    repeat(10) {<br>        try { <br>            emit(it)<br>        } catch(e: Exception) { <br>            print(&quot;this violates exception transparency!&quot;) <br>        }<br>    }<br>}</pre><p>An exception thrown in the collector would be caught in the new try/catch block! Furthermore the flow would just continue emitting the 10 values and catching exceptions on every new value.</p><p>The correct way to encapsulate exception handling in an emitter is to use the <strong><em>catch</em></strong> operator:</p><pre>fun strings() = listOf(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;).asFlow()<br>    .catch { cause: Throwable -&gt;<br>        // Inside the catch block you can:<br>        // - ignore, log or process the exception<br>        // - emit a new value using emit<br>        // - re-throw the same exception or a new one using throw<br>    }</pre><p>The <strong><em>catch</em></strong> operator catches only upstream exceptions.</p><p>If we want to handle exceptions in a declarative way, we could move the body of the <strong><em>collect</em></strong> operator into an <strong><em>onEach</em></strong>, add a <strong><em>catch</em></strong> operator after it and collect the flow using the terminal operator <strong><em>collect()</em></strong> without input parameters:</p><pre>numbers()<br>    .onEach {<br>        check(it &lt;= 1) { &quot;Crashed on $it&quot; }<br>        print(&quot;$it;&quot;)    <br>    }<br>    .catch { print(&quot;Exception caught(${it.message})!&quot;) }<br>    .collect()<br>// like the first example, this also prints:<br>// &quot;0;1;Exception caught(Crashed on 2)!&quot;</pre><h3>Completion</h3><p>Sometimes, when a flow completes (either normally or by throwing an exception), you might need to perform some action. This can be done in two ways:</p><pre>fun numbers() = (1..3).asFlow().map { &quot;it;&quot; }</pre><pre>try {<br>    numbers().collect { value -&gt; print(value) }<br>} finally {<br>    print(&quot;Done&quot;)<br>} // prints &quot;1;2;3;Done&quot;</pre><p>For a declarative approach, you can apply the intermediate operator <strong><em>onCompletion</em></strong> before collecting the flow:</p><pre>numbers()<br>    .onCompletion { cause: Throwable? -&gt;<br>        print(&quot;Done&quot;)<br>    }<br>    .collect { value -&gt; print(value) }<br>// also prints &quot;1;2;3;Done&quot;</pre><p>The advantage here is that the nullable parameter can be used to determine if the collection of the flow ended normally or with an exception.</p><p>An important thing to note is that, unlike <strong><em>catch</em></strong>, <strong><em>onCompletion</em></strong> does not handle the exception itself and it will still flow downstream. You must still use the operator <strong><em>catch</em></strong> or a try/catch block to handle the exception.</p><p>Another difference with the <strong><em>catch</em></strong> operator is that <strong><em>onCompletion</em></strong> sees all exceptions and receives a null exception only on successful completion of the upstream flow (without cancellation or failure): it’ll still receive the exception even if it’s thrown downstream, i.e. in the collector.</p><h3>Cancellation</h3><p>Flows adhere to the cooperative cancellation of coroutines (you can read more about coroutines and cooperative cancellation in my previous <a href="https://medium.com/@rkam88/kotlin-coroutines-in-android-summary-1ed3048f11c3">article</a>). A flow collection can be canceled when the flow is suspended in a cancellable function (like <strong><em>delay</em></strong>).</p><p>The <strong><em>flow</em></strong> builder performs additional checks with <strong><em>ensureActive</em></strong> before emitting each new value. That said, other builders (like <strong><em>asFlow</em></strong>) don’t perform cancellation checks for optimization reasons and you’ll have to check for cancellation explicitly. For this, you can use the <strong><em>cancelable() </em></strong>operator or add the following code to any flow before it’s collected:</p><pre>.onEach { currentCoroutineContext().ensureActive() }</pre><p>Note that all implementations of <strong><em>SharedFlow</em></strong> and <strong><em>StateFlow</em></strong> are cancelable by default too.</p><h3>Integration with other libraries</h3><p>Kotlin flows are supported in multiple libraries, including Retrofit, WorkManager, DataStore and Room.</p><p>For example, starting with version 2.2 of Room, you can specify a flow as the return type of functions in a DAO and be notified of changes in the database:</p><pre><a href="http://twitter.com/Dao">@Dao</a><br>abstract class ExampleDao {<br>    <a href="http://twitter.com/Query">@Query</a>(&quot;SELECT * FROM Example&quot;)<br>    abstract fun getExamples(): Flow&lt;List&lt;Example&gt;&gt;<br>}</pre><p>Ready-to-use converters for integration of flows with reactive streams such as RxJava are available in the corresponding modules of the coroutines library. Check the official <a href="https://kotlinlang.org/docs/flow.html#flow-and-reactive-streams">docs</a> for more info.</p><p>For LiveData interoperability, you can use the extension <strong><em>asLiveData()</em></strong> to convert a Flow to LiveData (available in the library androidx.lifecycle:lifecycle-livedata-ktx).</p><p>Just like with coroutines, where you can use <strong><em>suspendCancellableCoroutine</em></strong> to build a bridge between coroutines and a callback based API that returns a single value, you can use the <strong><em>callbackFlow</em></strong> builder to create a flow from any multi-shot callback API. A great explanation about both of them is available <a href="https://manuelvivo.dev/simplifying-apis-coroutines">here</a>.</p><h3>StateFlow and SharedFlow</h3><p>As mentioned before, Flows are cold by default. This means that if we subscribe to a Flow, the code in its builder will get executed each time we subscribe to it. This is something that you might not want to do when an Activity or Fragment goes through a configuration change. To solve this, <strong><em>StateFlow</em></strong> can be used.</p><p><strong><em>StateFlow</em></strong> is a hot observable that stores the latest value. When created, it requires you to pass an initial state to it and any observer can check its current value or subscribe to it at any time to receive updates with the current value as it changes.</p><pre>data class SomeState(<br>    val isLoading: Boolean = false,<br>    val data: String? = null,<br>)</pre><pre>val myState = MutableStateFlow&lt;SomeState&gt;(SomeState())</pre><pre>fun onLoadClicked() {<br>    myState.update { currentState -&gt; <br>        currentState.copy(isLoading = true)<br>    }<br>    viewModelScope.launch {<br>        val newData = repository.loadData()<br>        myState.update { currentState -&gt;<br>            currentState.copy(isLoading = true)<br>        }<br>    }<br>}</pre><p>Note that in the above example we don’t update the state by changing its value directly (which can lead to bugs if the state is being concurrently updated, especially when SomeState is a data class. A more detailed explanation about this possible bug can be found <a href="https://medium.com/geekculture/atomic-updates-with-mutablestateflow-dc0331724405">here</a>), but rather use the function <strong><em>update</em></strong> to change the value atomically.</p><p>You can also convert any flow to a <strong><em>StateFlow</em></strong> using the <strong><em>stateIn</em></strong> operator:</p><pre>val stateFlow: StateFlow&lt;SomeState&gt; = someFlow<br>    .stateIn(<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5000),<br>        initialValue = someInitialValue,<br>    )</pre><p>The started parameter is used to specify the strategy that controls when sharing is started and stopped. <strong><em>WhileSubscribed</em></strong> allows you to configure a delay in milliseconds between the time the last subscriber disappears and the time we stop the upstream flows. This can be used for cases when the app goes to the background to save battery and other resources, and still avoid restarting the upstream flow during configuration changes.</p><p>You might have noticed that <strong><em>StateFlow</em></strong> is very similar to LiveData, yet there are two big differences you should keep in mind:</p><ul><li><strong><em>StateFlow</em></strong> requires a an initial value</li><li>The method observe() from LiveData automatically unregisters the consumer when the view enters the STOPPED state. Flow collection is not stopped automatically, but this behaviour can be easily achieved with the <strong><em>repeatOnLifecycle</em></strong> extension.</li></ul><p>Another hot observable is <strong><em>SharedFlow</em></strong>, a highly-configurable generalization of <strong><em>StateFlow</em></strong>. It can be tuned, to specify the number of old events to keep and replay for new subscribers, an extraBufferCapacity parameter to provide support for backpressure (fast emitters and slow subscribers) and it can define a <strong><em>BufferOverflow</em></strong> strategy to either suspend the emitter or drop the oldest/newest emitted value. In its default form, it can be used to emit events that need to be handled once:</p><pre>MutableSharedFlow(<br>    replay = 0,<br>    extraBufferCapacity = 0,<br>    onBufferOverflow = BufferOverfow.SUSPEND<br>)</pre><p>An important thing to keep in mind about <strong><em>SharedFlow</em></strong>, is that in the absence of a subscriber (for example, if the event is posted during a configuration change) events will be immediately dropped and won’t reach the new subscriber, so it should be used for events that must be processed immediately or not at all.</p><p>For cases, such as processing navigation events, or showing a SnackBar, you might want to make sure that the event is retained until a subscriber appears. As suggested by Roman Elizarov in this <a href="https://elizarov.medium.com/shared-flows-broadcast-channels-899b675e805c">article</a>, this can be done by using a <strong><em>Channel</em></strong>:</p><pre>private val _events = Channel&lt;Event&gt;()<br>val events = _events.receiveAsFlow() // expose as flow</pre><pre>suspend fun postEvent(event: Event) {<br>    _events.send(event) // suspends on buffer overflow<br>}</pre><p>As stated above, <strong><em>SharedFlow</em></strong> is highly configurable. Please refer to the articles in the links bellow to get a better idea of the case it can be effectively used in.</p><h3><strong>Foreword</strong></h3><p>Kotlin flows are simple in design, yet offer many possibilities. I’ve tried to describe the most common and important aspects about them, but feel free to comment with any feedback if you think I missed something that should be included in this article.</p><h3><strong>Other useful links</strong></h3><ul><li><a href="https://medium.com/androiddevelopers/repeatonlifecycle-api-design-story-8670d1a7d333">repeatOnLifecycle API design story (article)</a></li><li><a href="https://www.youtube.com/watch?v=fSB6_KE95bU">Kotlin Flows in practice - Android Dev Summit 2021 (video)</a></li><li><a href="https://medium.com/androiddevelopers/migrating-from-livedata-to-kotlins-flow-379292f419fb">Migrating from LiveData to Kotlin Flow (article)</a></li><li><a href="https://medium.com/androiddevelopers/things-to-know-about-flows-sharein-and-statein-operators-20e6ccb2bc74">Things to know about flows shareIn and stateIn operators (article)</a></li><li><a href="https://rvbsoftdev.medium.com/kotlin-flows-an-android-cheat-sheet-d71ae772030d">Kotlin Flow cheat-sheet (article)</a></li><li><a href="https://kt.academy/article/cc-channel">Channel in Kotlin Coroutines (article)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e092040fb3a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-flows-in-android-summary-8e092040fb3a">Kotlin Flows in Android summary</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[Jetpack Compose in production code: first impressions]]></title>
            <link>https://proandroiddev.com/jetpack-compose-in-production-code-first-impressions-dd8fabd4a3c8?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd8fabd4a3c8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 20:50:05 GMT</pubDate>
            <atom:updated>2023-05-16T13:56:46.118Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Using Jetpack Compose in production code: first impressions</strong></h3><p>Since its announcement, Jetpack Compose seemed like a very promising framework and my colleagues at MTS Bank and I were waiting for its stable version to be released to try it out in production code. Last month we finally got the chance, when we decided to update the design of one of our app’s screens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*T-zlXHc6YyPekLVBGcxgqg.png" /></figure><p>In this article I’d like to talk about our experience with Jetpack Compose, the advantages it brings, share some best-practices of composable functions and also provide a few useful links along the way to help you get started with Compose. Hopefully you’ll find this article useful if you’re considering using Jetpack Compose in your projects.</p><h3>Interoperability</h3><p>We use the Single-Activity architectural approach in our app, so, as described in the docs, we just needed to change our implementation of the onCreateView() Fragment method to return a ComposeView with our screens UI.</p><pre>override fun onCreateView(...): View {<br>    return ComposeView(requireContext()).apply {<br>        setContent { /* In Compose world */ }<br>    }<br>}</pre><p>Something we noticed straight away is that the first launch of a screen with compose takes longer to load (over 1 second!). While investigating the reasons for this, a great <a href="https://engineering.premise.com/measuring-render-performance-with-jetpack-compose-c0bf5814933">article</a> was found with some explanations: it turns out that having R8 disabled and debuggability enabled increases the first-load time of Compose screens by around 0.5 seconds each. Also, the first screen with compose also takes almost twice as long as subsequent screens.</p><p>Some testing on our part confirmed this, so, as stated in the article above, using Compose might have a higher performance cost than you expect, and it’s something you should keep in mind, but it’s definitely not something critical that should stop you from starting to use it.</p><p>Click <a href="https://developer.android.com/jetpack/compose/interop/interop-apis">here</a> for more official compatibility information.</p><h3>Jetpack integration</h3><p>Accessing ViewModels directly in @Composable functions is possible by using the viewModel() function from the <a href="https://developer.android.com/jetpack/androidx/releases/lifecycle">lifecycle-viewmodel-compose</a> library (still in alpha) and modern DI frameworks (Koin, Dagger/Hilt) also provide support for this. But since we’re not changing out navigation graph and display our @Composable screen content inside a fragment, a simpler solution might be to just inject the ViewModel into the fragment itself like we did pre-compose and pass a reference to it (or the state that it produces) to the @Composable functions that needs it.</p><p><a href="https://developer.android.com/jetpack/compose/libraries">Here</a> you can find docs about integration with other libraries.</p><h3>Material design</h3><p>Because of the relatively small size of our experiment, there is not much to say on this topic. Note that the <a href="https://play.google.com/store/apps/details?id=androidx.compose.material.catalog">Material Design catalog</a> app will definitely come in handy when you’re starting out to see the components that are already implemented.</p><p>Another great resource is the official <a href="https://github.com/android/compose-samples/releases">compose-samples repository</a> in GitHub.</p><h3>Lists</h3><p>If you’ve seen at least a couple of videos of Compose, you probably already noticed how easy it is to create a RecyclerView (LazyList):</p><pre>@Composable<br>fun MessageList(messages: List&lt;Message&gt;) {<br>    LazyColumn {<br>        items(messages) { message -&gt; MessageRow(message) }<br>    }<br>}</pre><p>Also, it’s very easy to customize their behaviour:</p><p>One of the feats of the new design was a ViewPager with two groups of buttons, but at the time of writing this article, there’s still no official ViewPager in Compose. A <a href="https://github.com/google/accompanist">library</a> by Chris Banes has its own implementation and can serve as a solution to this problem, but it’s API is still marked as experimental (by the way, the library is used in official Jetpack Compose examples and might even become part of the framework itself in the future). The solution above might be totally fine for a pet project or some apps, using alpha libraries and experimental APIs is not something you’d want to do in a banking app.</p><p>A valid solution would be to just use the existing ViewPager in Compose with the help of the AndroidApi composable. Or, alternatively, we could just use a LazyRow for the content with some analogue of SnapHelper for RecyclerView. Compose currently doesn’t have one, but implementing one ourselves is a lot easier than you might think: you just need to pass a custom implementation of FlingBehavior to LazyRow.</p><p>You can check the full code <a href="https://gist.github.com/rkam88/5a5213f9f9289551be848c0023175d69">here</a>.</p><p>And this is how it looks, when combined with a Row of buttons synced with LazyRow’s LazyListState:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*JLdTw-SBYwtNXKVfBry5Fg.gif" /></figure><p>You can also find several great examples with code on various topics <a href="https://www.jetpackcompose.app/">here</a>.</p><h3>Animations</h3><p>This has to be one of my favourite features of Jetpack Compose, because it’s animation APIs are very easy to use. Just check the <a href="https://www.youtube.com/watch?v=7yY2OocGiQU">example</a> video from Android Developers<br>- it’s just 5 minutes, but contains examples for animations that will cover your needs most of the time. Yep, animations are that easy-to-use now.</p><h3><strong>Best practices for @Composable fun</strong></h3><p><strong><em>Follow the parameters order convention: obligatory parameters, modifier, parameters with default values, content.</em></strong></p><p>This is the way the standard library composables are written. Let’s see why the order matters using the function that we made for a quick implementation of a collapsing toolbar as an example:</p><pre>@Composable<br>fun CollapsingToolbar(<br>    title: String,<br>    modifier: Modifier = Modifier,<br>    navigationIcon: NavigationIcon? = null,<br>    config: CollapsingToolbarConfig = CollapsingToolbarConfig(),<br>    scrollState: ScrollState = rememberScrollState(),<br>    content: @Composable ColumnScope.() -&gt; Unit,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*roeO5HWSl1sAal8AOOIQyw.gif" /></figure><p>Having the Modifier parameter first or after any obligatory parameters allows you to specify it without explicitly writing it’s name at the callsite:</p><pre>@Composable<br>fun MyScreen() {<br>    CollapsingToolbar(<br>        title = &quot;My title&quot;,<br>        Modifier.fillMaxSize(),<br>        navigationIcon = NavigationIcon(R.drawable.ic_arrow_right){<br>            /* handle click logic */<br>        },<br>    ) {<br>        // trailing lambda with content!<br>    }<br>}</pre><p>Putting the content parameter last allows you to use trailing lambdas.</p><p>Standard library examples: any composable function.</p><p><strong><em>Use helper classes to hold related parameters together.</em></strong></p><p>There are two helper classes in the above example:</p><pre>class CollapsingToolbarConfig(<br>    val collapsedToolbarHeight: Dp = 56.dp,<br>    val expandedToolbarHeight: Dp = 112.dp,<br>    val collapsedTitleStartPadding: Dp = 72.dp,<br>    val expandedTitleStartPadding: Dp = 20.dp,<br>    val collapsedTitleFontSize: TextUnit = 20.sp,<br>    val expandedTitleFontSize: TextUnit = 32.sp,<br>)<br>class NavigationIcon(<br>    @DrawableRes val icon: Int,<br>    val onClick: (() -&gt; Unit)<br>)</pre><p>Using helper classes like the ones above allow us to group together the parameters of our toolbar to improve code readability.</p><p>Note that NavigationClass was used to combine the icon for the toolbar and the callback that should be invoked when it’s clicked. We won’t need a callback if there is no icon to draw, so combining them is a good idea.</p><p>Standard library examples: TextStyle, PaddingValues, SwitchDefaults to name a few.</p><p><strong><em>Make stateful and stateless versions of your composables.</em></strong></p><p>If you’re going to have a composable with state, you might as well let the caller use state hoisting (in compose: the pattern of moving state to a composable’s caller to make a composable stateless). LazyRow and LazyColumn have their state defined as a default parameter, so that the caller of the function can control the state and change it if needed. We did the same in our example with the parameter scrollState, that is passed to a Column that holds the content with Modifier.verticalScroll(scrollState). For now, the default value is always used, but since we need to initiate the state somewhere anyway, there is nothing wrong in doing so in the function declaration as a default parameter and it’ll give our function more flexibility for the future.</p><p>Another important convention is that functions that hold state, should be named with the “remember” prefix.</p><p>Examples: rememberLazyListState(), rememberCoroutineScope().</p><p><strong><em>Use the scope of the content as the receiver for content functions.</em></strong></p><p>In Compose, modifiers are extension functions and some of them are only available in the scope of their composables (BoxScope, ColumnScope, etc). For example, the ColumnScope defines an align() modifier:</p><pre>interface ColumnScope {<br>    fun Modifier.align(alignment: Alignment.Horizontal): Modifier<br>}</pre><p>In our <em>CollapsingToolbar</em> example, we defined the parameter <em>content</em> as:</p><pre>content: @Composable ColumnScope.() -&gt; Unit</pre><p>So, at the call site the scope is available and we’re able to apply modifiers to the content that we would not be able to do otherwise.</p><pre>CollapsingToolbar(<br>    title = &quot;My title&quot;,<br>) { <strong>this: ColumnScope<br>    </strong>Text(<br>        text = &quot;some text&quot;,<br>        Modifier.align(Alignment.CenterHorizontally)<br>    )<br>}</pre><p>Standard library examples: any composable function with content.</p><p><strong><em>Remember to keep your code DRY (don’t repeat yourself).</em></strong></p><p>This is more actual than ever. Of course we had the &lt;include&gt; tag in xml, and we could even pass parameters to included layouts with DataBinding, but copy pasting xml views and modifying a parameter or two was usually faster and easier. Nowadays, for composables, extracting the code of an item and reusing it is easier than ever. Just please remember to use Android Studio’s hotkeys while doing so: command+option+m or ctrl+alt+m for Mac/Windows.</p><h3>Afterword</h3><p>In our app, we already use a MVI approach with a single observable in ViewModels that holds the current state of the view and unidirectional data flow, so the business logic in the VM remained untouched and integration with Compose was really easy in that regard. One of the only concerns that we have left is that some of the framework’s APIs are still experimental (sticky headers for lazy lists, no out-of-the-box ViewPager and no animations for list changes as some examples). You might find some things you need missing and you’ll need to either write your own implementation of some view or behaviour or use the interoperability API to include old views in compose (WebView and MapView being the most common examples). Either way, considering all of the advantages it brings, it’s clear that any Android developer should start becoming familiar with it as soon as possible.</p><blockquote>A version of this article in Russian is available <a href="https://habr.com/ru/company/ru_mts/blog/588096/">here</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd8fabd4a3c8" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-in-production-code-first-impressions-dd8fabd4a3c8">Jetpack Compose in production code: first impressions</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[Using CoroutineContext to repeat failed HTTP request]]></title>
            <link>https://proandroiddev.com/using-coroutinecontext-to-repeat-failed-http-request-9d7092d8cec1?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7092d8cec1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 10:14:08 GMT</pubDate>
            <atom:updated>2021-12-21T19:37:49.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*vENtPk08IcC0Ie-7GUDVsA.png" /></figure><p>A common scenario in Android applications is the need to repeat a request when something goes wrong, for example when there are problems with the users internet connection.</p><p>Let’s assume that we have a screen with several HTTP requests and we need to show a dialog that lets the user retry the request that failed.</p><p>If the screen had only one request — the task would be pretty straightforward: just call the method again. But if the screen has several requests that can be called at different times we need a way to identify the function that was called. Storing the last called function is a possible solution, but it’s not very flexible: if some requests don’t need to show a “Try again” dialog we must clear the variable after a success and forgetting to do this can lead to bugs.</p><p>A simple solution to the problem above can be to use <strong>CoroutineContext</strong> to save the function we need to call again later.</p><p>By default, <strong>CoroutineContext</strong> is composed of the elements <strong>Job</strong>, <strong>CoroutineDispatcher</strong>, <strong>CoroutineName</strong> and <strong>CoroutineExceptionHandler </strong>(you can read more about it in my previous <a href="https://medium.com/@rkam88/kotlin-coroutines-in-android-summary-1ed3048f11c3">article about Coroutines</a>). But, as stated in the docs, <strong>CoroutineContext</strong> is an indexed set of <strong>Element</strong> instances, so we can create our own implementation of the <strong>Element</strong> interface, by extending the class <strong>AbstractCoroutineContextElement</strong>:</p><pre>class RetryCallback(val callback: () -&gt; Unit) :<br>   <strong>AbstractCoroutineContextElement</strong>(RetryCallback) {<br>   companion object Key : CoroutineContext.Key&lt;RetryCallback&gt;<br>}</pre><p>Now, we can just add an instance of our custom RetryCallback element to the <strong>CoroutineContext</strong> of any coroutine we start:</p><pre>fun someFunction(someParam: List&lt;String&gt;) {<br>   viewModelScope.launch(exceptionHandler<br>      + <strong>RetryCallback { someFunction(someParam) }</strong>) {<br>      // perform the request, update the view with the result<br>   }<br>}</pre><p>And if the request fails we can can access the callback in the <strong>CoroutineExceptionHandler</strong>:</p><pre>private val exceptionHandler = CoroutineExceptionHandler {<br>   coroutineContext, throwable -&gt;<br>   val callback: (() -&gt; Unit)? = <strong>coroutineContext[RetryCallback.Key]<br>                                    ?.callback</strong><br>   // ...<br>}</pre><p>From the <strong>CoroutineExceptionHandler</strong> we can just pass the function to our <strong>Activity</strong> or <strong>Fragment</strong> and invoke it once the user clicks the “Try again” button.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7092d8cec1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/using-coroutinecontext-to-repeat-failed-http-request-9d7092d8cec1">Using CoroutineContext to repeat failed HTTP request</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 Coroutines in Android Summary]]></title>
            <link>https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3?source=rss-bc0767d43086------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed3048f11c3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Roman Kamyshnikov]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 11:02:27 GMT</pubDate>
            <atom:updated>2025-02-09T04:15:34.943Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a concise summary of various articles and talks about the use of Kotlin coroutines in Android. For in-depth details on any of the covered topics, check out to the links provided at the end. Please note, that the use of Kotlin Flow is not covered here to keep the article short.</p><h3>Intro</h3><p>Coroutines build upon regular functions by adding two new operations (in addition to <strong><em>invoke</em></strong>/<strong><em>call</em></strong> and <strong><em>return</em></strong>):</p><ul><li><strong><em>suspend</em></strong> — pauses the execution of the current coroutine, saving all local variables. The current thread can continue with its work, while the suspending code runs on another thread.</li><li><strong><em>resume</em></strong> — continues a suspended coroutine from the place it was paused when the result is ready.</li></ul><p>These operations work together to replace callbacks.</p><p>This functionality is added by marking a function with the <em>“</em><strong><em>suspend</em></strong>” keyword. You can only call suspend functions from other suspend functions, or by using a coroutine builder to start a new coroutine.</p><h3>Structured concurrency</h3><p>Kotlin introduced structured concurrency — a combination of language features and best practices that, when followed, help you keep track of all work running in coroutines. On Android we use it for 3 things:</p><ul><li>Cancel work when it is no longer needed.</li><li>Keep track of work while it’s running.</li><li>Signal errors when a coroutine fails.</li></ul><p>Structured concurrency guarantees:</p><ul><li>When a scope cancels, all of its coroutines cancel.</li><li>When a suspend function returns, all of its work is done.</li><li>When a coroutine errors, its caller or scope is notified.</li></ul><p>Coroutines must run in a <strong><em>CoroutineScope</em></strong>, which is used to keep track of all the coroutines, and it can cancel all of the coroutines started in it. When a scope cancels, all of its coroutines cancel. <strong><em>CoroutinesScope</em></strong> propagates itself — new coroutines started by your coroutines will have the same scope.</p><p>In Android it often makes sense to associate a <strong><em>CoroutineScope</em></strong> with a user screen (usually by starting coroutines in a ViewModel). When the user leaves the screen — the associated <strong><em>CoroutineScope</em></strong> can cancel all the work.</p><p>Coroutines are cancelled cooperatively by throwing a <strong><em>CancellationException</em></strong> when the coroutine is suspended. If you consume the <strong><em>CancellationException</em></strong> in a low-level handler or never suspend, the coroutine will linger in a semi-canceled state.</p><h3>CoroutineScope</h3><p>Starting a coroutine requires a <strong><em>CoroutineScope</em></strong> that takes <strong><em>CoroutineContext</em></strong> as a parameter to its constructor. The later is composed by the elements:</p><ul><li><strong><em>Job</em></strong> — controls the lifecycle of the coroutine.</li><li><strong><em>CoroutineDispatcher</em></strong> (default is <strong><em>Dispatchers.Default</em></strong>) — dispatches work to the appropriate thread.</li><li><strong><em>CoroutineName</em></strong> (optional, default is “coroutine”) — name of the coroutine, useful for debugging.</li><li><strong><em>CoroutineExceptionHandler</em></strong> (optional) — handles uncaught exceptions.</li></ul><p>When creating a <strong><em>CoroutineContext</em></strong>, the elements can be combined with the “+” operator:</p><pre>val myContext: CoroutineContext = Job() + Dispatchers.Main<br>val myScope = CoroutineScope(myContext + CoroutineName(&quot;my name&quot;))</pre><h3>Job</h3><p>Either <strong><em>Job</em></strong> or <strong><em>SupervisorJob</em></strong> can be used. <strong><em>Job</em></strong> cancels all its children if one of them fails. <strong><em>SupervisorJob</em></strong> — doesn’t, so you should usually use <strong><em>SupervisorJob</em></strong> for the top-level scope.</p><p>A job can go through the states: New, Active, Completing, Completed, Cancelling and Cancelled. We don’t have access to the states, but we can access the following properties: <strong><em>isActive</em></strong>, <strong><em>isCancelled</em></strong> and <strong><em>isCompleted</em></strong>.</p><p>If the coroutine is Active, a coroutine failure or calling <strong><em>job.cancel()</em></strong> will change the state of the job to Cancelling (<strong><em>isActive</em></strong> = false, <strong><em>isCancelled</em></strong> = true). Once all children have completed their work the coroutine will go in the Cancelled state and <strong><em>isCompleted</em></strong> = true.</p><h3>CoroutineDispatcher</h3><p>Used to specify where the coroutine should run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-5ZG6rVR5Dl9J5E3Rx7eA.png" /><figcaption>* Libraries like Room or Retrofit — handle threading automatically. They also have coroutine support: just add the “suspend” modifier to the functions of an API or DAO interface and the dependency “androidx.room:room-ktx:$room_version” for Room.</figcaption></figure><blockquote>Edit: There’s also <strong>Dispatchers.Unconfined</strong>, a dispatcher that starts the coroutine in the calling thread, but after a suspension point resumes in whatever thread that is used by the corresponding suspending function. Note that it’s an advanced mechanism that can be helpful in certain corner cases but, as stated in the official docs, it should not be used in general code. Big thanks to <a href="https://medium.com/@tufanov">Denis Tufanov</a> for pointing this out.</blockquote><h3>Existing scopes</h3><ul><li>In ViewModels you can use the extension property <strong><em>viewModelScope</em></strong> to start coroutines. Under the hood, it uses a <strong><em>CoroutineContext</em></strong> with <strong><em>SupervisorJob</em></strong> and <strong><em>Dispatchers.Main</em></strong>. When the ViewModel is cleared, it executes the clear method before calling onCleared. In the clear method the ViewModel cancels the Job of the <strong><em>viewModelScope</em></strong>.</li><li>For <strong><em>LiveData</em></strong> — the KTX <strong><em>liveData</em></strong> can be used to call a suspend function and return the result of it as a <strong><em>LiveData</em></strong> object:</li><li>There are also lifecycle aware scopes: lifecycle.<strong>coroutineScope</strong> and lifecycleOwner.<strong>lifecycleScope</strong>. They are available from a Lifecycle or from a LifecycleOwner (Activity or Fragment), but using them is not recommended</li></ul><p>The dependencies for the scopes above are:</p><pre>androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha07<br>androidx.lifecycle:lifecycle-livedata-ktx:2.3.0-alpha07<br>androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha07</pre><p>For operations that should not be canceled <strong><em>GlobalScope</em></strong> can be used, but a better alternative would be creating a custom scope in the Application class, and inject it to the class that needs it. This has the advantage of giving you the ability to use <strong><em>CoroutineExceptionHandler</em></strong> or replace the <strong><em>CoroutineDispatcher</em></strong> for testing.</p><p>Example:</p><pre>class MyApplication : Application() {<br>   val myAppScope = CoroutineScope(SupervisorJob() + otherConfig)<br>}</pre><p>Note that <strong><em>SupervisorJob</em></strong> is used to prevent exceptions of a child canceling its siblings and that there’s no need to cancel the scope: it’ll be torn down with the process.</p><p>You can use this scope inside other coroutines in the following way:</p><pre>suspend fun someUseCaseFunction() {<br>   myAppScope.launch { veryImportantOperation() }.join(<br>   // or<br>   myAppScope.async { veryImportantOperation() }.await()<br>}</pre><h3>Creating new coroutines</h3><p>Once you have a <strong><em>CoroutineContext</em></strong>, you can use the methods <strong><em>launch()</em></strong> or <strong><em>async()</em></strong> to start a new coroutine</p><ol><li><strong><em>launch()</em></strong> — starts a new coroutine that is “fire and forget” — that means it won’t return the result to the caller.</li><li><strong><em>async()</em></strong> — starts a new coroutine, and it allows you to return a result with a suspend function called <strong><em>await()</em></strong>.</li></ol><p>Since a regular function can’t call the suspend function <strong><em>await()</em></strong> — usually it makes sense to start the coroutine with <strong><em>launch()</em></strong>.</p><p>Every coroutine you create:</p><ul><li>returns a <strong><em>Job</em></strong> that can be used to manage its lifecycle.</li><li>inherits the <strong><em>CoroutineContext</em></strong> from its parent (another coroutine or the <strong><em>CoroutineScope</em></strong>) and overrides the context parameters if you specify any.</li></ul><p>Note: the parent-child relationship between scopes and coroutines is created using <strong><em>Job</em></strong> objects.</p><p>In general, you should start coroutines in the main thread by using <strong><em>Dispatchers.Main</em></strong>, so that if you don’t end up doing a long running task — the result will be available in the next frame for the user.</p><h3>Switching dispatchers</h3><p>Inside a coroutine you can switch them at any time by using <strong><em>withContext()</em></strong>:</p><pre>suspend fun get(url: String) =<br>   /* perform some work on Dispatchers.Main */<br>   withContext(Dispatchers.IO) { /* some work on Dispatchers.IO */ }<br>   /* perform some more work on Dispatchers.Main */</pre><p>The coroutine will suspend, allowing the main thread to do other work, and resume to continue execution after the block inside <strong><em>withContext()</em></strong> returns.</p><p>Several calls to <strong><em>withContext()</em></strong> with the same dispatcher are optimized to stay on the same thread. Switching from <strong><em>Dispatchers.IO</em></strong> to <strong><em>Dispatchers.Default</em></strong> is also optimized to prevent thread switching if possible.</p><h3>Simultaneous work</h3><p>To perform work simultaneously you can use <strong><em>coroutineScope()</em></strong> or <strong><em>supervisorScope()</em></strong>.</p><p>They handle exceptions differently and <strong><em>coroutineScope()</em></strong> will cancel whenever any of its children fail and <strong><em>supervisorScope()</em></strong> won’t cancel other children when one of them fails.</p><p>The <strong><em>coroutineScope()</em></strong> builder will suspend itself until all coroutines started inside of it are complete (or one of them fails by throwing an exception):</p><pre>suspend fun fetchTwoDocs() {<br>   val list: List&lt;Document&gt; = coroutineScope {<br>      val doc1: Deferred&lt;Document&gt; = async { fetchDoc(1) }<br>      val doc2: Deferred&lt;Document&gt; = async { fetchDoc(2) }<br>      launch { fetchDoc(3) } // use launch if no result is needed<br>      <br>      return@coroutineScope listOf(doc1.await(), doc2.await())<br>   }<br>}</pre><p>Note: all coroutines in the example above have the same <strong><em>CoroutineScope</em></strong>: the one used to start the initial coroutine that called the fetchTwoDocs function.</p><p>You can use <strong><em>await()</em></strong> with coroutineScope when you want to do two things simultaneously and use the combined result after both are done.</p><p>For jobs created with <strong><em>launch()</em></strong>, you can call <strong><em>job.join()</em></strong> to suspend the coroutine until the job completes.</p><h3>One-shot requests and concurrency patterns</h3><p>Usually the best and simplest solution is just disabling the UI (button) that is used to trigger the request.</p><p>Also, to handle one-shot request being called several times (double clicks on buttons for example) there are three concurrency patterns:</p><ol><li>Cancel previous work before starting more.</li><li>Queue the next work and wait for the previous requests to complete before starting another one.</li><li>Join previous work if there’s already a request running just return that one instead of starting another request.</li></ol><p>Two classes that implement the concurrency patterns above can be found <a href="https://gist.github.com/objcode/7ab4e7b1df8acd88696cb0ccecad16f7#file-concurrencyhelpers-kt-L19">here</a>.</p><h3>Exception handling</h3><p>If a coroutine (including ones started in other coroutines) doesn’t handle exceptions by itself with a <strong><em>try-catch</em></strong> clause, the exception isn’t re-thrown: it is “propagated up the job hierarchy” and can be handled by a <strong><em>CoroutineExceptionHandler</em></strong>.</p><p><strong><em>CoroutineExceptionHandler</em></strong> must be added to the scope or the top-level coroutine to catch exceptions.</p><pre>val exceptionHandler = CoroutineExceptionHandler {<br>   coroutineContext, exception -&gt; /* handle exception */ <br>}</pre><pre>val topLevelScope = CoroutineScope(Job() + exceptionHandler)<br>// or<br>topLevelScope.launch(exceptionHandler) { … }</pre><p>If the coroutine does not handle the exception with a <strong><em>try-catch</em></strong> and no <strong><em>CoroutineExceptionHandler</em></strong> is present — the uncaught exception handler of the thread is invoked! A try-catch around a top-level coroutine will not catch these exceptions.</p><p>Use <strong><em>try-catch</em></strong> if you want to retry the operation or do other actions before the Coroutine completes (in this case, the exception isn’t propagated up the job hierarchy).</p><p>Use <strong><em>CoroutineExceptionHandler</em></strong> for logic that should happen after the coroutine completes.</p><p>Uncaught exceptions in both <strong><em>launch()</em></strong> and <strong><em>async()</em></strong> are immediately propagated up the job hierarchy.</p><p><strong><em>coroutineScope()</em></strong> re-throws exceptions of its failed child coroutines instead of propagating them up the job hierarchy. This lets you handle exceptions of failed coroutines with <strong><em>try-catch</em></strong>.</p><p><strong><em>supervisorScope()</em></strong> installs a new independent sub-scope with a SupervisorJob as the job of the new scope. This new scope does not propagate its exceptions and has to handle exceptions on its own.</p><p>Coroutines that are started directly from the <strong><em>supervisorScope()</em></strong> are top-level coroutines. Because of this — you can use a <strong><em>CoroutineExceptionHandler</em></strong> in them.</p><p>Top-level coroutines, including those in a <strong><em>supervisorScope(), </em></strong>behave differently than child coroutines when they are started with <strong><em>launch()</em></strong> or <strong><em>async()</em></strong> and their behavior depends on the coroutine used to start them:</p><ul><li>If the top-level coroutine was started with <strong><em>launch()</em></strong>, the exception can be handled by a <strong><em>CoroutineExceptionHandler</em></strong>.</li><li>If the top-level coroutine was started with <strong><em>async()</em></strong>, the exception is encapsulated in the <strong><em>Deferred</em></strong> return type and re-thrown when <strong><em>.await()</em></strong> is called on it.</li></ul><h3>Cancelation</h3><p>You can use the <strong><em>cancel()</em></strong> method of a <strong><em>Job</em></strong> or <strong><em>CoroutineScope</em></strong> to cancel jobs.</p><p>Canceling the scope also cancels its children. Canceling a child doesn’t affect other siblings.</p><p>Coroutines are canceled by throwing a CancellationException. This can be used to handle cancelation. When canceling, you can provide your own instance of it as a parameter to <strong><em>cancel()</em></strong> to provide details about the cancellation reason.</p><p>Once you cancel a scope, you won’t be able to launch new coroutines in the cancelled scope.</p><h3>Making coroutines cancelable</h3><p>Cancellation should be cooperative: the code running won’t stop by its own.</p><p>Suspend functions from <strong><em>kotlinx.coroutines</em></strong> (<strong><em>withContext()</em></strong> for example) are cancelable, for other functions — you can check manually if the coroutine was canceled in the following ways:</p><ul><li><strong><em>job.isActive</em></strong> — this lets you perform other actions when canceling but requires an if statement.</li><li><strong><em>job.ensureActive()</em></strong> — throws a <strong><em>CancellationException</em></strong> immediately.</li><li><strong><em>CoroutineScope.yield()</em></strong> — can be used work that is CPU heavy, may exhaust the thread pool or if you want to allow the thread to do other work without having to add more threads to the pool. The first operation done by yield will check for completion and throw a <strong><em>CancellationException</em></strong> if the job is not active (<strong><em>isActive</em></strong>=false).</li></ul><p>A good place for <strong><em>yield()</em></strong> or <strong><em>ensureActive()</em></strong> can be the start of each cycle of a work-heavy loop.</p><h3>Job and Deferred differences</h3><p>For Jobs — calling <strong><em>job.cancel()</em></strong> and <strong><em>job.join()</em></strong> after will suspend the current coroutine until the job completes.</p><p>For Deferred — calling <strong><em>deferred.cancel()</em></strong> and then <strong><em>deferred.await()</em></strong> throws JobCancellationException.</p><p>Calling <strong><em>cancel()</em></strong> after <strong><em>job.join()</em></strong> or <strong><em>deferred.await()</em></strong> has no effect.</p><h3>Handling side-effects</h3><p>Two options:</p><ul><li>Check for !<strong><em>isActive</em></strong>.</li><li>Since <strong><em>CancellationException</em></strong> is thrown, you can wrap the code in a <strong><em>try-catch</em></strong> and put the clean-up code in the <strong><em>finally</em></strong> block.</li></ul><p>Note: after cancellation the coroutine is in the Canceled state and it can’t suspend anymore. If you need to suspend — use <strong><em>withContext(NonCancellable) { … }</em></strong> for the clean-up if needed. Use <strong><em>NonCancellable</em></strong> only for suspending clean-up code.</p><h3>Best practices</h3><p>1. Every suspend function should be main-safe.</p><p>2. Always inject Dispatchers into classes. It makes testing easier since you can replace them in unit and instrumentation tests.</p><p>3. The ViewModel/Presenter layer should create coroutines. The UI layer should be “dumb” and not trigger any business logic.</p><p>4. The layers below the ViewModel/Presenter layer should expose suspend functions and Flows. Use <strong><em>coroutineScope</em></strong> or <strong><em>supervisorScope</em></strong> if you need to create additional coroutines. The caller (usually a ViewModel) will be able to control the execution, lifecycle and cancelling.</p><p>5. Prefer using a custom scope, created in the Application class, over <strong><em>GlobalScope</em></strong> or <strong><em>lifecycleScope</em></strong>. They require you to inject a custom <strong><em>CoroutineContex</em></strong> to control the lifecycle of the coroutines. <strong><em>lifecycleScope</em></strong> also requires you to inject ProcessLifecycleOwner.get() and use a fake in tests.</p><p><strong><em>2022 Update:</em></strong><em> Since the time this article was written, there have been some changes to Coroutine testing. This section has been updated with the new API and official </em><a href="https://developer.android.com/kotlin/coroutines/test"><em>recommendations</em></a><em> from google.</em></p><h3>Testing Coroutines: tests that don’t create new coroutines</h3><p>In order to test simple suspending functions that don’t create new coroutines, just wrap your test using <strong><em>runTest()</em></strong>:</p><pre>fun someTest = <strong><em>runTest</em></strong> {<br>   someSuspendingFunction()<br>   // assert something happened<br>}</pre><p>This will also skip any delays, unless the suspending function uses withContext() to switch dispatchers.</p><h3>Testing Coroutines: tests that create new coroutines</h3><p>This is usually the case for the ViewModel layer, where most coroutines are created.</p><p>First, inject a dispatcher into the class that creates the coroutine, and during tests — replace it with a <strong><em>TestDispatcher</em></strong> and use <strong><em>runTest()</em></strong>. There are two <strong><em>TestDispatcher</em></strong> implementations that schedule new coroutines in different ways:</p><ul><li><strong><em>StandardTestDispatcher</em></strong> — new coroutines are queued up on the underlying scheduler and run whenever the test thread is free to use. This resembles the standard coroutine behaviour and lets you control how coroutines are run. In order to yield the test thread, you can use <strong><em>runCurrent()</em></strong>, <strong><em>advanceTimeBy()</em></strong> or <strong><em>advanceUntilIdle()</em></strong>. This is the default dispatcher that <strong><em>runTest</em></strong> will use.</li><li><strong><em>UnconfinedTestDispatcher</em></strong> — new coroutines will be started immediately in the current thread.</li></ul><p>Both use a <strong><em>TestCoroutineScheduler</em></strong> to control virtual time and manage coroutines. For proper behaviour, all dispatchers inside the scope of <strong><em>runTest</em> </strong>must use the same scheduler.</p><pre>val testDispatcher = TestCoroutineDispatcher()</pre><pre>fun `test buttonClicked`() = runTest { // this: TestScope<br>   val viewModel = SomeViewModel(<br>      // the same scheduler from Test scope is used<br>      StandardTestDispatcher(this.testScheduler)<br>   )</pre><pre>   viewModel.onButtonClicked()<br>   // assert something happened<br>}</pre><p>For android, you will often need to provide an implementation of <strong><em>Dispatchers.Main</em></strong> for the test. The easiest way for this is to use a JUnit rule:</p><pre>class MainDispatcherRule(<br>    val testDispatcher: TestDispatcher = <em>UnconfinedTestDispatcher</em>(),<br>) : TestWatcher() {<br>    override fun starting(description: Description) {<br>        Dispatchers.<em>setMain</em>(testDispatcher)<br>    }<br>    override fun finished(description: Description) {<br>        Dispatchers.<em>resetMain</em>()<br>    }<br>}<br><br>class SomeViewModelTest {<br>    @get:Rule<br>    val mainDispatcherRule = MainDispatcherRule()<br><br>    @Test<br>    fun settingMainDispatcher() = <em>runTest </em><strong>{ </strong>// Uses Main’s scheduler<br>        val viewModel = SomeViewModel()<br>        viewModel.onButtonClicked()<br>        // assert something happened<br>    }<strong><br></strong>}</pre><p>Any feedback will be greatly appreciated! Please don’t hesitate to leave a comment if you think I missed out something or some part could be reworded to be shorter or clearer.</p><h3>Links</h3><ul><li><a href="https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb">Coroutines in Android article series (3 part article)</a></li><li><a href="https://medium.com/androiddevelopers/coroutines-first-things-first-e6187bf3bb21">Cancelation and exceptions article series (3 part article)</a></li><li><a href="https://medium.com/androiddevelopers/easy-coroutines-in-android-viewmodelscope-25bffb605471">viewModelScope and how it works (article)</a></li><li><a href="https://www.lukaslechner.com/why-exception-handling-with-kotlin-coroutines-is-so-hard-and-how-to-successfully-master-it">Exception handling with Kotlin coroutines (article)</a></li><li><a href="https://medium.com/androiddevelopers/the-suspend-modifier-under-the-hood-b7ce46af624f">The suspend modifier under the hood (article)</a></li><li><a href="https://www.youtube.com/watch?v=KMb0Fs8rCRs">Testing with kotlinx.coroutines.test (video)</a> (Old coroutines API)</li><li><a href="https://www.youtube.com/watch?v=hzTU0lh-TIw">Untangling coroutines testing (video)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed3048f11c3" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3">Kotlin Coroutines in Android Summary</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>
    </channel>
</rss>