<?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 Halil Ozercan on Medium]]></title>
        <description><![CDATA[Stories by Halil Ozercan on Medium]]></description>
        <link>https://medium.com/@halilozercan?source=rss-e41a22a47844------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s7l2_R5Q51VMWLGcBIH_Ug.png</url>
            <title>Stories by Halil Ozercan on Medium</title>
            <link>https://medium.com/@halilozercan?source=rss-e41a22a47844------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:13:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@halilozercan/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[Markdown Rendering and Recursive Composition]]></title>
            <link>https://itnext.io/markdown-rendering-and-recursive-composition-e76cca3631e8?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/e76cca3631e8</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[render]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 13:43:23 GMT</pubDate>
            <atom:updated>2021-07-04T21:15:20.830Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever thought about how this article is rendered on your screen? We all know about fonts, font sizes, bold/italic/underlined styling, paragraphs, bullet points but have you ever actually thought about the steps behind this process? A part of the text can be <strong>bold </strong>or <em>italic</em> but where is that information stored? Although there is no indicator in the text itself, this statement reminds us one of our favorite markup languages.</p><p>You are most likely familiar with Markdown which sits as a bridge between the two worlds of formatted and plain text. It lets you stylize your text in a plain text editor and any compatible renderer would turn it into a nice stylized document. Github README files, slack chat messages, Reddit comments, all support a version of Markdown. Although WYISWYG editors usually output documents in XML or JSON formats which are adapt for machine readability, Markdown is advantageous in terms of being human readable without much distraction.</p><p>In this post I want to solely focus on how Markdown helps with converting a styleable text into plain text as well as how would a UI framework like Compose go on to covert that plain text into a beautiful looking, styled document.</p><h3>Markdown Parsing</h3><p>Markdown documents are not pre-processed, meaning that they are written, storred, and transferred as they are. A Markdown Renderer receives the plain text content directly. Then, the renderer would be responsible for converting the text into a structured document. For the rest of this section, I’ll be basing the parsing on <a href="https://github.com/commonmark/commonmark-java">Commonmark</a> library.</p><blockquote>Hello, **World!**</blockquote><p>Above text is an obvious one for Markdown readable people. However, it is not instantaneously apparent for a word processor to understand what those (*) stars mean. An intermediate renderer must know all the Markdown rules to interpret the text in a structured way for a text renderer to stylize it. When this text is given to Commommark parser, output looks like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTSWbwz16Qq95dJmd3A4lg.png" /></figure><p>We can of course go further and mix it up a bit</p><blockquote>Hello, **Wo_rld_!**</blockquote><p>Then, this would correspond to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ysa4tr7sIaO9AslESu1bQ.png" /></figure><p>We are starting to get a hang of how a text block is stylized internally. Bold, Italic, Strikethrough, Underline, Link, inline images, and etc. would all follow the same approach when applied. On the other hand, paragraph is not an inline style but considered as a text block. Text blocks include but not limited to; bullet points, code blocks, quotes, and numbered lists. Lastly, let’s add a bullet point to our example before moving on with the data structure behind the parsed result.</p><blockquote>Hello,</blockquote><blockquote>- **Wo_rld_!**</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*ms6dE7MjMNvOXMPmf_SFrA.png" /></figure><p>Finally, we have 2 text blocks where one of those also includes inline styling.</p><p>So, the last question is how would a parser output its result? It actually depends on what the consumer is going to do with it. If we are only thinking about parsing and storing the result for future use, the output can be a JSON or XML that resembles an HTML document. However, Commonmark is a multi-purpose parser that is available in different languages. We will be talking about the Java version. It would be wasteful to get JSON or XML as an output because they would need to be further parsed to be used in whatever UI framework we are working in. Instead, Commonmark gives us a tree which is not very surprising. Looking at the last example, we can easily imagine it as a tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a07MesyxJ47Uq_7HjJnEGg.png" /></figure><p>Although it looks convoluted, this tree is very easy to reason about. It starts with a Document tag at the root. Its children are expected to be blocks that contain Text. First paragraph has a single child that says “Hello” without any styling, pretty simple. Second child declares itself to be a list item so we assume that there is going to be a bullet point at the left side of this block. Only child under it is of a styling nature. “Bold” tree node declares that all of its children need to be stylized with Bold rule. So, “Wo”, whatever under “Italic”, and “!” are all need to be bold. Same situation applies to the children of “Italic” node, meaning that “rld” is going to be both Bold and Italic.</p><h3>Trees, Recursion, Traversal</h3><p>Anyone who has spent sometime with any UI framework would tell you that all UI is actually a tree of components. Compose is no different and actually makes it quite apparent. Even further, Compose is split into two parts in which an abstract dynamic tree is updated with the latest state and the other part spits out UI according to the changes in this tree. Here are a few resources for curious ones to learn more</p><p><a href="https://jakewharton.com/a-jetpack-compose-by-any-other-name/">A Jetpack Compose by any other name - Jake Wharton</a></p><h3>Jorge Castillo 🍋 on Twitter: &quot;When thinking about Compose it&#39;s good to notice that Composables don&#39;t yield actual UI, but &quot;emit&quot; changes to the in-memory structure managed by the runtime (slot table) via the Composer. That representation has to be interpreted later on to &quot;materialize&quot; UI from it 🧵 pic.twitter.com/qKNhe8wyOp / Twitter&quot;</h3><p>When thinking about Compose it&#39;s good to notice that Composables don&#39;t yield actual UI, but &quot;emit&quot; changes to the in-memory structure managed by the runtime (slot table) via the Composer. That representation has to be interpreted later on to &quot;materialize&quot; UI from it 🧵 pic.twitter.com/qKNhe8wyOp</p><p>Our Markdown tree from earlier aligns very well with Compose. The only thing we need to do is traverse the tree while emitting corresponding Composables. This correspondence can be quite simple as in we should have Composables for text blocks which accept a content parameter that would include children. I haven’t mentioned this yet but text blocks can include other text blocks in a Markdown spec.</p><p>Let’s start with some code examples</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6ac850a488fe7b1ec0f1d7a8271d97/href">https://medium.com/media/fd6ac850a488fe7b1ec0f1d7a8271d97/href</a></iframe><p>This gist shows what kind of composable tree we are expecting for our Markdown example. Function names and call order is completely arbitrary at this point. We are going to use <a href="https://github.com/zach-klippenstein/compose-richtext">compose-richtext</a> library for building blocks later on. For now, our attention should be on how to traverse a parsed Markdown Tree while emitting Composables.</p><p>Axioms are useful while working on complex systems to define some boundaries. Hence, it’s a good idea to determine those axioms at the beginning for a solid implementation plan.</p><ul><li>Every document starts with a Document node.</li><li>Text and styling nodes reside always under a text block e.g. Paragraph, Quote, ListItem, etc.</li><li>Text is a terminal node. Text cannot have children.</li><li>Styling does not leak to other text blocks. Style nodes cannot have text block as children.</li><li>All Text Blocks must have Paragraph as their first child e.g. BlockQuote -&gt; Paragraph -&gt; Content</li></ul><p>A generic view of a Markdown node is as follows:</p><pre>Node:<br>  - leftChild<br>  - rightChild<br>  - next<br>  - previous</pre><p>In our example, we will also have a children iterable that goes from the most left child to the most right.</p><p>It’s quite predictable that recursively traversing this tree while emitting Text Block composables would be the way to go. An almost pseudo code for that is given below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d38ff8ffb33bb86d0a9c8d8f56ba98/href">https://medium.com/media/e3d38ff8ffb33bb86d0a9c8d8f56ba98/href</a></iframe><p>Node is supposed to be a sealed class that has subtypes of all the defined text blocks under our Markdown documentation. Given that we have iteration helpers and text blocks that are available from compose-richtext, it looks almost too easy. It is nearly enough to call render from root node and the rest should work out. Unfortunately, text inside a paragraph might be defined as a tree but cannot computed in a recursive way. Please refer to the first code example where Text blocks are called separately. Compose is going to treat those text calls as separate Text composables, therefore the output would actually be series of independent Text layouts.</p><p>Instead, our axioms tell us that once we encounter a Paragraph, we can safely assume the rest of the children are going to be either Text or styling nodes. From there on out, we can compute a stylized text block that is undividable.</p><p>Although recursion does not work, we can do a pre-order traversal while building a spanned text. The complete code for this process can be found <a href="https://github.com/zach-klippenstein/compose-richtext/blob/main/richtext-commonmark/src/main/java/com/zachklipp/richtext/markdown/MarkdownRichText.kt#L55">here</a></p><p><a href="https://github.com/zach-klippenstein/compose-richtext/blob/main/richtext-commonmark/src/main/java/com/zachklipp/richtext/markdown/MarkdownRichText.kt#L55">zach-klippenstein/compose-richtext</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Ff-eaGnRNU-3y1puu2NnkQ.gif" /></figure><p>Pre-order traversal for building a spanned string is explained in the gif above. Styling nodes push a span into ongoing builder, text nodes append their content to the builder. In the end, a spanned, or a RichText, is ready to be called with a single Text node. For the rest, we can continue with the recursive method.</p><h3>Conclusion</h3><p>I must admit I skipped tons of steps while trying to simplify this topic. Anyone who I got their attention and might have lit a spark in their interest towards this kind of topic can check out the whole compose-richtext library.</p><p><a href="https://github.com/zach-klippenstein/compose-richtext">zach-klippenstein/compose-richtext</a></p><p>The complete implementation of this Markdown renderer can be found below richtext-commonmark module. It’s a very rough implementation so contributions are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e76cca3631e8" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/markdown-rendering-and-recursive-composition-e76cca3631e8">Markdown Rendering and Recursive Composition</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Animations in Real Time]]></title>
            <link>https://proandroiddev.com/compose-animations-in-real-time-6068f10595ba?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/6068f10595ba</guid>
            <category><![CDATA[frame-rate]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 14:33:38 GMT</pubDate>
            <atom:updated>2021-06-11T21:32:50.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*wac7tkozLGkEx7EFOYVNJw.gif" /><figcaption><a href="https://nbasic.net/apps/particles.html">https://nbasic.net/apps/particles.html</a></figcaption></figure><p>A while ago I saw this animation on /r/internetisbeautiful. I highly recommend you <a href="https://nbasic.net/apps/particles.html">go</a> check it out for yourself on your browser. It sure looks better in 60 fps and also way smoother in 120+ fps. Although there is nothing fancy going on, small details in the animation makes it quiet nice to watch. Naturally, I’ve decided to implement it using Jetpack Compose. I thought there would be fun challenges behind a simple animation like this when I dive into the implementation details. Initially my assumption was</p><ul><li>Number of dots would complicate things performance wise</li><li>Line width should be inversely proportional to the distance between dots</li><li>High number of dots might cause a frame to lag above frame seconds limit.</li></ul><p>The first concern turned out to be not a serious one thanks to realistically low(less than a million) number of dots and the ability of modern phones to run O(n²) algorithms like a kid’s toy.</p><p>The last concern is the biggest one in any heavy loaded animation. Games would never feel natural on a weak machine if they drew every frame no matter how long it takes to actually draw a frame. When a frame is late to the party, it should be dropped and game should resync with the wall clock. You can learn more about this at <a href="https://en.wikipedia.org/wiki/Frame_rate">Wikipedia</a>.</p><p><a href="https://en.wikipedia.org/wiki/Frame_rate">Frame rate - Wikipedia</a></p><p>Let’s assume we have the perfect device that can calculate and draw every frame in a nanosecond. We can sketch our design and finally address this non-existent perfect machine at the end while drawing everything.</p><h3>State</h3><p>One of the foundational blocks of Jetpack Compose is the state. State describes a picture in time for the whole environment without any sense of continuity. Compose has other building blocks (Animation Library, coroutines) that help us give life to a state in a continuous timeline.</p><p>Given what kind of animation we are trying to achieve, it’s not that difficult to figure out what kind of information do we need to draw a single frame.</p><ul><li>Dots (Position, Speed)</li></ul><p>We will have more information in state as part of implementation detail and additional configuration options but we don’t need anything else for the basic mental version. All we need are the DOTS!!</p><p>A very basic structure of a Dot can be as follows</p><pre>data class Dot(<br>    val position: Offset,<br>    val vector: Offset<br>)</pre><p>I used Offset as vector because it offers a distance function that spares us from writing a simple square root operation…</p><p>Drawing the state on screen is going to require us to define a certain threshold where dots start a connection. This threshold does not have to be part of the internal state of animation because it will not interest us while calculating the next iteration of state. The distance threshold will only be useful while drawing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db876617ae11dc28f0dc84729337972/href">https://medium.com/media/0db876617ae11dc28f0dc84729337972/href</a></iframe><p>I’m omitting lots of code here that you can find in the original repository. See the bottom of this page.</p><h3>Put the dots in the state</h3><p>Essentially, we leave the state empty with no dots because we have no idea how big or small the drawing area is going to be. I’d rather have number of dots that is proportional to container size. Also, initial position of all these dots are going to be random. How can we randomize the position without knowing the boundaries first? Of course we can use ratios to a percentage but it would hinder our ability to calculate boundary collisions in the next steps. In this case, a very useful modifier reaches to our help:</p><pre><em>onSizeChanged </em><strong>{ newSize -&gt;<br>    </strong>dotsAndLinesState = dotsAndLinesState.<em>sizeChanged</em>(<br>        size = <strong>newSize</strong><br>    )<br><strong>}</strong></pre><blockquote>You can and should use BoxWithConstraints for this task. However, original implementation is actually a background modifier written with composed modifier builder. I’ll use chained modifiers that consume a mutable state.</blockquote><p>sizeChanged function that we define as an extension on DotsAndLinesState is designed to work continuously even when size changes unexpectedly, not just for the first size update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f6065b5588486f1b2f533067cf4f380/href">https://medium.com/media/3f6065b5588486f1b2f533067cf4f380/href</a></iframe><p>findPopulation is left as an implementation detail. Original code binds it to another configurable option to easily control the population through a slider.</p><h3>Next Frame</h3><p>An immutable state that has information about dots helped us to draw a single frame. Now, it’s time for Compose to do its magic. If we wrap this state with remember { mutableStateOf { .. } } , every update to this state should notify consumers (a Canvas) to re-compose themselves.</p><pre>var dotsAndLinesState by <em>remember </em><strong>{<br>    </strong><em>mutableStateOf</em>(<br>        DotsAndLinesState()<br>    )<br><strong>}</strong></pre><p>The most crucial part of making this animation right would be the calculation of next state. So, when will we have the next step? <strong>Whenever we can</strong>. We are not going to force our animation to some constant FPS value. Even if we did that, an older device might have trouble rendering 30 FPS with 100 dots animating at the same time. The actual answer to “when next step” question is exactly putting that <em>when </em>into the calculation as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1f69667aee51abcdfff05f301444192/href">https://medium.com/media/d1f69667aee51abcdfff05f301444192/href</a></iframe><p>next function should mainly take care of 2 things;</p><ul><li>Collision detection with borders</li><li>Find where the dot will land according to its vector</li></ul><blockquote>Note: This implementation completely ignores the case where speed is so high that the dot should actually bounce from both sides at the same time. Traveling at such speeds will never be possible in our system ;)</blockquote><p>Introduction of durationMillis is going to be the key for smooth animation in any device with either low or high computation power. We simply follow newton’s physics in this iteration function.</p><h3>Respecting the frame rate</h3><p>Finally, we arrive at the main point of this article. Compose offers multiple Animation APIs that serve different needs from very simple position animations to complicated state transitions. You can learn more about these APIs from <a href="https://developer.android.com/jetpack/compose/animation">this awesome doc page</a>.</p><p>I want to highlight an API that is even more fundamental that concerns individual frames. Without further ado</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84e4636aa893629492a79b6458f70e77/href">https://medium.com/media/84e4636aa893629492a79b6458f70e77/href</a></iframe><p>We start a LaunchedEffect from our composed modifier that runs as long as this modifier is part of the composition tree. Later, while(isActive) makes sure that next iteration runs indefinitely.</p><pre><em>/**<br> * Awaits the next animation frame and returns frame time in nanoseconds.<br> */<br></em>public suspend fun awaitFrame(): Long</pre><p>awaitFrame waits the next frame and gives us the exact(nano) time that frame was drawn so that we can keep track of the wall clock and calculate our state iterations accordingly. We hold onto the result of awaitFrame at each iteration of outer loop because we are actually interested in the time between frames. We update our mutable state at the end of white loop block according to how many milliseconds have passed.</p><p>This gives us a very smooth and flexible animation that can handle 120 FPS devices as well as very old devices that cannot even produce 20 FPS for larger states (state iteration is O(n²)).</p><h3>Implementation</h3><p>Here you can find the original implementation that I repeatedly mentioned in the article</p><p><a href="https://github.com/halilozercan/madewithcompose/tree/main/dotsandlines/src/main/java/com/halilibo/dotsandlines">https://github.com/halilozercan/madewithcompose/tree/main/dotsandlines/src/main/java/com/halilibo/dotsandlines</a></p><p>Also, an older video that showcases the first implementation with multiple configuration options.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiCe5f7L9vBg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiCe5f7L9vBg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiCe5f7L9vBg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f612201a8e41d9711b99223119e335d5/href">https://medium.com/media/f612201a8e41d9711b99223119e335d5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6068f10595ba" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/compose-animations-in-real-time-6068f10595ba">Jetpack Compose Animations in Real Time</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[Deep Dive Into Lifecycle Coroutines]]></title>
            <link>https://medium.com/swlh/deep-dive-into-lifecycle-coroutines-e7192312faf?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7192312faf</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[androidx]]></category>
            <category><![CDATA[lifecycle-coroutines]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[lifecycle]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 17:01:41 GMT</pubDate>
            <atom:updated>2021-01-14T22:38:53.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive Into Android Lifecycle Coroutines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7rzSzsy-tlwsxic7V5SFA.jpeg" /></figure><p>Lifecycle Coroutine Extensions were introduced some time ago to ease the usage of coroutines in Android world. You can learn more about them <a href="https://developer.android.com/topic/libraries/architecture/coroutines">here</a>.</p><p>In this post, I’m going to assume the reader already has experimented with lifecycleCoroutineScope in either at least one activity or fragment. Although the documentation gives quite good information about how to use these extension scopes, I find it’s a little mystical about how these extensions are actually implemented.</p><p>In this post, we are going to read the source code together and make sense of some coroutine concepts with cross-references to some other documentation that we might need.</p><p>Most of the article might be redundant for speed-code-readers. Thus, I came up with a repeated structure for the whole post, so those readers can skip through uninteresting parts to them. The structure looks like this;</p><p><strong>Subject</strong></p><ol><li><strong>👩‍💻 Code</strong> that needs dissecting</li><li><strong>🤓 Reading</strong> the code with references to docs</li><li><strong>🏫 Learning</strong> points in one or two sentences (highlighted)</li></ol><p>Let’s start with our entry point from a LifecycleOwner to the coroutine world.</p><h3><strong>lifecycleCoroutineScope</strong></h3><h3>👩‍💻 Code</h3><pre>val LifecycleOwner.<em>lifecycleScope</em>: LifecycleCoroutineScope<br>    get() = <em>lifecycle</em>.<em>coroutineScope</em></pre><p>There is nothing much to talk about here. This extension value is simply a delegate to another extension field that is defined on a Lifecycle object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b63e606060cd8b3e6dd9c36a934be5f/href">https://medium.com/media/4b63e606060cd8b3e6dd9c36a934be5f/href</a></iframe><h3>🤓 Reading</h3><p>It’s always a good idea to start the reading from the documentation when it’s available. This time, the documentation is pretty straight-forward. It mentions that this scope is tied to the lifecycle that it’s defined on and will be cancelled when the corresponding lifecycle is DESTROYED . However, our first key take-away is mentioned the last;</p><blockquote>This scope is bound to Dispatchers.Main.immediate</blockquote><p>We will definitely touch on this while reading the implementation of this special scope. For now, we can continue with the actual implementation of the extension value.</p><p>We are immediately in for a surprise from the first line while(true) . That’s quite interesting because why would there be a need to endlessly try to return a coroutine scope? We will get to this in a minute.</p><pre>val existing = mInternalScopeRef.get() as LifecycleCoroutineScopeImpl?</pre><p>This is also strange but expected. If you check out the source code of ViewModel class as well, you are going to see a similar field called mBagOfTags . These are internal references to hold any extension value related to coroutines or anything else that might come up later. In this case, we see that lifecycle might already be holding to a LifecycleCoroutineScopeImpl from before. In that case, extension value getter returns this <em>existing </em>field.</p><p>Otherwise, a new LifecycleCoroutineScopeImpl is initialized and put in this AtomicReference object (mInternalScopeRef) if it’s currently null. At this point, we understand why this function is wrapped in an endless loop.</p><p>Here we need to make a note of two things.</p><ul><li>LifecycleCoroutineScopeImpl requires a coroutineContext and SupervisorJob() + Dispatcher.Main.immediate is passed.</li><li>Once newScope is successfully put inside mInternalScopeRef , register function is called.</li></ul><p>Remembering these 2 points will help us make sense of the actual implementation of this scope.</p><p>Learning the difference between Dispatchers.Main and Dispatcher.Main.immediate is crucial before moving forward. I’m going to directly refer to the documentation here. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-coroutine-dispatcher/immediate.html">https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-coroutine-dispatcher/immediate.html</a></p><blockquote>Returns dispatcher that executes coroutines immediately when it is already in the right context (e.g. current looper is the same as this handler’s looper) without an additional re-dispatch.</blockquote><p>Immediate dispatcher is quite important if we are already on the main thread and working on Android Views or animations. This dispatcher enables us to execute any code immediately on the main thread without waiting for scheduling to get into effect.</p><h3>🏫 Learned</h3><ul><li>lifecycleCoroutineScope is kind of a lazy property</li><li>lifecycleCoroutineScope uses Main.immediate</li></ul><p>Next, we will focus on the class that enables us to mix Lifecycle world with the coroutine world;</p><h3>LifecycleCoroutineScopeImpl</h3><h3>👩‍💻 Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e15bdffeda0634479a2f2d2d90f9d39/href">https://medium.com/media/4e15bdffeda0634479a2f2d2d90f9d39/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f152ec2d838d3d8b7461374f44e72f44/href">https://medium.com/media/f152ec2d838d3d8b7461374f44e72f44/href</a></iframe><p>I removed the repetitive documentation parts from LifecycleCoroutineScope abstract class to make it more compact for readability.</p><h3>🤓 Reading</h3><p>This class looks fun and more approachable. We should check out the base class and which interfaces are implemented before checking out the default constructor because it clearly uses override values.</p><p><strong>LifecycleCoroutineScope:</strong> An abstract class that holds onto a lifecycle object. It has no abstract functions but defines 3 different functions that can launch new coroutines on the given lifecycle from the parent. To make things more confusing, it extends from CoroutineScope. So, it can launch coroutines in on itself.</p><p><strong>LifecycleEventObserver:</strong> Implementing this interface enables LifecycleCoroutineScopeImpl to add itself as an observer to any lifecycle object. I believe things started to get real confusing for me at this point.</p><p>Looking at the constructor, we see that this class simply requires a coroutineContext to make itself a proper CoroutineScope and a lifecycle object to listen to lifecycle events. As we all know that this scope will respect the lifecycle, that’s the whole point.</p><p>The class definition starts with an init statement right away. It is there to check whether this lifecycle is already destroyed because this class might be initialized from a thread different thread than Main.</p><p>We remember the register function from lifecycleCoroutineScope extension value. It is called right after this class is initialized. The sole purpose of this function is to a launch a new coroutine to be ran in the Main thread to start listening to lifecycle events. It is crucial that this check runs on Main dispatcher because accessing lifecycle state from any other thread is considered unsafe.</p><p>register adds this class as an observer to the given lifecycle property, which brings us to onStateChanged . Again, this function has a very basic purpose; cancel the coroutineContext when lifecycle is destroyed.</p><h3>🏫 Learned</h3><ul><li>LifecycleCoroutineScopeImpl is a CoroutineScope</li><li>Through listening to lifecycle events, LifecycleCoroutineScopeImplcan cancel itself when lifecycle is DESTROYED.</li></ul><p>Let’s summarize our findings to understand our current toolbox better.</p><blockquote>We have access to a special kind of CoroutineScope through either a LifecycleOwner or Lifecycle object. This scope only starts if the lifecycle is initialized and gets cancelled when the lifecycle is destroyed. Also, this scope uses Dispatchers.Main.immediate as coroutine context.</blockquote><p>Anyone can launch a coroutine on LifecycleCoroutineScopeImpl at anytime. However, the real power behind this scope comes from the functions defined under LifecycleCoroutineScope abstract class. These functions take the form of launchWhenX . They are very similar to each other in a sense that they are executed when lifecycle is at least in stage X which can be either CREATED , STARTED , or RESUMED .</p><p><strong>📣 Important Notice: </strong>launchWhenX are not replacements to onCreate, onStart, or onResume in activities or fragments. They only guarantee that the lambda that’s passed to the function is executed when the conditions in lifecycle is ready. The execution can be immediate, or at a future point.</p><p>Before deep diving into these functions, we should see what is the difference between them.</p><pre>= lifecycle.whenCreated(block)<br>= lifecycle.whenStarted(block)<br>= lifecycle.whenResumed(block)</pre><p>Ok.. These look like simple delegations. Let’s go one step further.</p><pre>whenStateAtLeast(Lifecycle.State.<em>CREATED</em>, block)<br>whenStateAtLeast(Lifecycle.State.STARTED, block)<br>whenStateAtLeast(Lifecycle.State.RESUMED, block)</pre><p>Hmm.. They are actually calling the same function with different parameters. Maybe deep diving directly into this function makes more sense. However, we should not forget that</p><pre>fun launchWhenCreated(block: suspend CoroutineScope.() -&gt; Unit): Job = <em>launch </em><strong>{</strong></pre><p>All launchWhenX functions start with a launch call on LifecycleCoroutineScope . So, whenStateAtLeast suspendable function is actually called on this new coroutine. We should keep that in mind while evaluating.</p><h3>whenStateAtLeast</h3><h3>👩‍💻 Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b50b843e6ee7c60cbedeb385a572582b/href">https://medium.com/media/b50b843e6ee7c60cbedeb385a572582b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d83ad9f2e08c8591bdd959067f964b54/href">https://medium.com/media/d83ad9f2e08c8591bdd959067f964b54/href</a></iframe><h3>🤓 Reading</h3><p>Here we finally have the real deal because things will get very tricky from now on. First of all, we should always remember that we are simply in a suspendable function which is supposed to run in a LifecycleCoroutineScope ‘s child coroutine. Let’s start from first line;</p><pre>withContext(Dispatchers.Main.immediate)</pre><p>Once again, we are making sure whatever that is going to happen in this function, happens in the main thread.</p><pre>val job = coroutineContext[Job] ?: error(...</pre><p>Access the job of parent coroutine. <a href="https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#job-in-the-context">https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#job-in-the-context</a></p><pre>val dispatcher = PausingDispatcher()</pre><p>PausingDispatcher is one of the few cases that I’m not going to dive in because it deserves its own post. In a nutshell, PausingDispatcher is a special kind of CoroutineDispatcher that includes a dispatching queue which can be paused and resumed at any given time.</p><pre>val controller =<br>    LifecycleController(this@whenStateAtLeast, minState, dispatcher.dispatchQueue, job)</pre><p>LifecycleController will be the glue that holds everything together at this point. It has access to the minimum lifecycle state that is required to dispatch our coroutine in a PausingDispatcher . I also included the source code for this class.</p><p>LifecycleController has a very similar structure to LifecycleCoroutineScopeImpl . It is a lifecycle event observer that manipulates the dispatchQueue upon lifecycle changes. When state is at least minState , queue resumes. If lifecycle is destroyed, parentJob gets cancelled. Finally, it pauses the dispatchQueue in any other case. By simply creating this controller, lifecycle events and PausingDispatcher are linked together.</p><pre>try {<br>    withContext(dispatcher, block)<br>} finally {<br>    controller.finish()<br>}</pre><p>Finally, we simply run the given block in this special dispatcher. Also, controller is informed to seize its observation when the execution ends.</p><p>In the end, we have a way of running coroutines that are paused, resumed, and cancelled upon significant lifecycle events and these coroutines are dispatched in Dispatchers.Main.immediate + PausingDispatcher .</p><p><strong>📣 Important Takeaway: </strong>launchWhenX functions are not cancelled when lifecycle leaves the desired state. They simple get paused. Cancellation happens only if lifecycle reaches DESTROYED state. This is way too important if you are collecting flows in one of these coroutines. Your collection won’t end if your activity or fragment simply goes to background. It will only get paused. So, you don’t have to restart your collection at each onStart or onResume.</p><h3>🏫 Learned</h3><ul><li>launchWhenX functions also use Dispatchers.Main.immediate</li><li>whenStateAtLeast suspend functions do not actually depend on usage of LifecycleCoroutineScope . They can be called from any coroutine.</li><li>Be very careful if you are going to use withContext or flowOn in launchWhenX functions because they will modify the context(PausingDispatcher) that your code runs in. <strong>Do not forget</strong> that the parent coroutineScope still gets cancelled at only DESTROYED event. Changing the dispatcher might have unforeseen consequences if not thoroughly tested.</li><li>Everytime you call a launchWhenX function, a new LifecycleController , a new PausingDispatcher gets allocated. Don’t be very generous with running too many coroutines with these launcher functions.</li></ul><p>In this article, I’ve tried to get into the implementation of coroutine extensions and learn its inner workings. Coroutines are easier to grasp but harder to master and there are many small details that might go missing from the unexperienced eye. Those small things usually come back to bite you when they are the least expected. Thus, I believe it’s beneficial for everyone to have at least one skim through over the actual code that implement the API that we will be using <em>hopefully</em> for a long time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7192312faf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/deep-dive-into-lifecycle-coroutines-e7192312faf">Deep Dive Into Lifecycle Coroutines</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Fragment Result API]]></title>
            <link>https://proandroiddev.com/taming-the-fragment-result-api-2fa85b448198?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fa85b448198</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[fragments]]></category>
            <category><![CDATA[fragment-result]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 22:58:51 GMT</pubDate>
            <atom:updated>2022-10-02T15:02:57.757Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: This article is written by a developer who have not yet migrated their fragments to Jetpack Navigation Component, therefore lack crucial experience in it. Although the author have researched the use-cases of Fragment Result within Navigation Component, some of the things that are discussed below may not hold in some unforeseen situations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nff-27y6utNvp1Cdn03hmw.png" /></figure><p>Fragment Result API was introduced in Fragment artifact of AndroidX with the version 1.3.0-alpha04 . Since then, it hasn’t received many changes to either its API or implementation detail. Its main goal was noted in the release notes:</p><blockquote>Added support for passing results between two Fragments via new APIs on FragmentManager. This works for hierarchy fragments (parent/child), DialogFragments, and fragments in Navigation and ensures that results are only sent to your Fragment while it is at least STARTED</blockquote><p>At the same time another method for passing data between fragments was deprecated.</p><blockquote>The target fragment APIs have been deprecated. To pass data between fragments the new Fragment Result APIs should be used instead</blockquote><p>These changes were quite a relief because there were multiple options for passing data between fragments at the time and none of them felt like the right thing to do for their own reasons. Let’s start by briefly going over them and understand why FragmentResult was a necessity.</p><h3>The old ways</h3><h4>Target Fragment</h4><p>TargetFragment had been the recommended way of passing a result from a fragment to parent fragment. Its API leveraged the already existing onActivityResult method in fragments. Simply, a fragment could return its result in a way that is very similar to Activities. To learn more about it you can check out this post</p><p><a href="https://medium.com/better-programming/what-is-target-fragment-da0e7c7f345c">What Is a Target Fragment?</a></p><p>There wasn’t a particular problem with targetFragment until Navigation Component had arrived. When parent fragment wanted to start e.g., a dialog fragment which would return a selected item, it simply called setTargetFragment and child fragment could easily return the result to parent’s onActivityResult . It was just a convenient way to pass the parent fragment information to a child fragment. However, Navigation Component handles fragment creation including arguments in which there is no control over setting the target fragment.</p><p>Recommended way of handling this problem at the beginning was to use of shared ViewModels. However, using shared ViewModels to just deliver result data between a child and parent could be called an anti-pattern. It requires a single ViewModel that governs both views at the same time. This approach could get infeasible very fast in the case of merging two very different ViewModels just to achieve a data exchange.</p><p>Therefore, targetFragment was deprecated at the same time FragmentResult was introduced.</p><h4>Callbacks</h4><p>There is not much to discuss about callbacks. They are comfortable, favorable, easy to follow and adheres to traditional way of assessing results from a callee to a caller. However, they come with a HUUUGE drawback. Once the activity is destroyed for some reason and recreated, the fragment backstack is also reinitialized with initial arguments as well as what was saved during onSaveInstanceState phase. Unfortunately, callback lambdas are lost forever. There is no lambda implementation that can be put in a bundle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/920d5b0eef829a84d573dc1bd6a81689/href">https://medium.com/media/920d5b0eef829a84d573dc1bd6a81689/href</a></iframe><h4>Activity Interfaces</h4><p>Introducing an interface in the activity that can receive the result from a fragment is the oldest but the safest way. But again, this doesn’t really cover fragment to fragment scenario which is our main goal with the Navigation Component. In a SingleActivity world, almost all communication is going to happen between fragments. Although they are still very useful, activity interfaces don’t help us in this quest. On a side note, it wouldn’t hurt to find a solution that can also easily replace Activity interfaces so that we have a unified solution for both <em>fragment to activity</em> and <em>fragment to fragment</em>.</p><h3>FragmentResult is … verbose?</h3><p>I can attempt to explain the inner workings of FragmentResult and how to use it properly but I would definitely butcher it. So if you have questions about it and you’re not in a hurry, I again would like to suggest reading the official documentation and the post I shared below.</p><ul><li><a href="https://developer.android.com/training/basics/fragments/pass-data-between">Pass data between fragments | Android Developers</a></li><li><a href="https://proandroiddev.com/android-fragments-fragment-result-805a6b2522ea">Android Fragments: Fragment Result</a></li></ul><p>Let’s take a look at the examples from the documentation. In the end, we might have some questions regarding the ease of using this API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6626901aaa2753fc19d32f71ebe094fc/href">https://medium.com/media/6626901aaa2753fc19d32f71ebe094fc/href</a></iframe><p>This is the example given in official docs for the API. Although fragment-ktx is optional, I definitely recommend including it in your dependencies because it properly takes advantage of Kotlin.</p><p>What we see in this example is the sample code for how parent fragment is able to listen to the result that is provided by a child or sibling fragment. Fragment-unawareness is the first thing that catches our attention. We are not setting something like targetFragment to the child fragment nor we are defining it in this listener setup. All that is expected is a request key and a bundle key. Let’s keep that in mind for future reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d12d11f04c2b6d98939c21e2e07d30af/href">https://medium.com/media/d12d11f04c2b6d98939c21e2e07d30af/href</a></iframe><p>Above code is the example for the fragment that wants to return a result. Once again, it doesn’t care about the type of the parent or actually which parent we are passing this result to. Only configurables that are apparent in this example are request key and bundle key.</p><h4>What about the keys?</h4><p>It’s all cool and nice that these examples demonstrate the fact that Fragment Result is approachable and can replace the older methods quickly. However, there is something that is grossly overlooked in the documentation: &quot;requestKey&quot; , &quot;bundleKey&quot; . Would you be OK with having constant values defined in-place? In most circumstances, these keys would be better defined as constant values in companion objects.</p><pre>private const val REQUEST_KEY = &quot;requestKey&quot;<br>private const val BUNDLE_KEY = &quot;bundleKey&quot;</pre><p>Are we done? Not really. Let’s talk about a scenario where you may call a dialog fragment for different results. For example, parent fragment needs to receive a start date and an end date from a child fragment. You need to differentiate between the two results coming for both start and end date. How would you do that? Easy, just use different request keys. This introduces a new kind of problem; you need to make sure the child fragment knows which request key you are using. Easy, just pass the request key through the arguments. Wait, hold up! This added a little bit verbosity on both ends.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6325446cb0397063f0ab43ac42042465/href">https://medium.com/media/6325446cb0397063f0ab43ac42042465/href</a></iframe><p>Both the parent fragment and child fragment needs to figure out which request key to use. We haven’t even talked about bundle or result key that is going to be the key for result in the bundle. That also needs to be added as a constant value in either child or parent fragment.</p><p>In the above example, we also assumed that the arguments were non-existent to begin with. What if the child fragment already had a factory function such as newInstance() ? Wouldn’t it be risky to make public interface changes so that we can have the advantages of FragmentResult?</p><p>Before moving forward with introducing a plain approach to get rid of this verbosity, let’s make assumptions on general use cases.</p><ol><li>Most fragments return a single result. We can think of them as functions. Even when they have multiple values to return, they can be wrapped in a bundle. In the end, result can be anything that is Parcelable</li><li>Request Keys are not constant. This can still be configurable.</li><li>Most common use-case is one-to-one where an activity or a fragment calls a child fragment only for a single objective. This default behavior should be achieved very easily.</li></ol><h3>Rizalt</h3><p>I have to admit that there is no alternative to setFragmentResult and setFragmentResultListener when it comes to naming. Adding helper functions that also have the same name with similar signature would be quite confusing. That’s why I had to choose a different name just for the sake of it. Rizalt is the Turkish spelling of how Result is pronounced in English.</p><p>I will give you the full implementation of Rizalt down below but let’s first talk about what kind of methods that we are going to need and why?</p><p>Starting with; we are going to need to mark the child fragment that it is intended to have a return value. This way, all our helper functions can be written as extensions on that type.</p><p>Secondly, it is necessary to create a customizable request key that also has a default value when it’s not cared for.</p><p>Third, result key should also be inferred by looking at the child fragment and doesn’t need customization. Our first assumption was that the result would be a single return value.</p><p>Finally, alternatives for setFragmentResult and setFragmentResultListener which are all aware of these keys that were created and passed in the background.</p><p>So, here we have the implementation for Rizalt .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b814264168c258312ed6ddcc4665e1/href">https://medium.com/media/53b814264168c258312ed6ddcc4665e1/href</a></iframe><p>And example usage</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/884a27ff4832c6dd1782151c6fd48231/href">https://medium.com/media/884a27ff4832c6dd1782151c6fd48231/href</a></iframe><p>The idea is as follows;</p><ul><li>As long as you have no need for a custom request key, it can be omitted. Default request key will always be calculated.</li><li>When custom request key is required, it can be used in result listener for different requests but it is not really needed when registering the result from child. At that point the request key can be either read from arguments or again calculated by default value.</li><li>setFragmentResultListener now knows about the fragment class, rather than a String. It’s more natural to me that result listener actually knows which fragment it is listening to instead of using an arbitrary string.</li><li>Whatever can be inferred, should be inferred. Result listeners now receive the exact return type that is defined in Rizalt interface, rather than a bundle.</li><li>setFragmentResult was simple and OK, so the API for it is not modified. However, the new function also supports the default bundle key.</li></ul><h3>Conclusion</h3><p>This write-up turned out to be longer than I intended at the beginning but I wanted to be thorough so that what is introduced is adequately justified. FragmentResult is awesome but it required adding a bit verbosity to our current codebase which didn’t feel right. This approach also introduced compile-time type check and inference which would be lost by passing bundles between fragments and then casting Parcelables to intended types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fa85b448198" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/taming-the-fragment-result-api-2fa85b448198">Taming the Fragment Result API</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[ProgressBar animations with Espresso]]></title>
            <link>https://proandroiddev.com/progressbar-animations-with-espresso-57f826102187?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/57f826102187</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 10:45:49 GMT</pubDate>
            <atom:updated>2020-09-18T19:31:36.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Zw6bFCJYkA5KfE0537hGw.jpeg" /></figure><p>It is not uncommon that once you run into an issue with Intrumentation Testing in Android, you’d feel like the loneliest person in the world. This might be an unforeseen effect of abundance of Android knowledge that exists on the Internet. Whatever you search for, there is always a StackOverflow answer or a Medium article that exactly describes what you need to do. However, this doesn’t hold for testing. My assumption is that this trend would hold in many other areas of Software Engineering. Although TDD is being popularized, it is still fairly rare, especially among one-developer teams which is unfortunately very common in mobile teams.</p><h4><strong>Problem: Animations in Espresso</strong></h4><p>Espresso has quite a bit obsession with idleness. Any action or assertion on views first require everything to settle on UI. In other words, if anything is still moving on your screen, Espresso will happily wait before executing any command. This doesn’t necessarily cause a problem if we are talking about transition or window animations that take fraction of a second. However, what happens if we want to show a ProgressBar or some sort of drawable that is animated when the screen goes into a loading state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34d8a7b4e1582efcd7b9ee3eb42e3334/href">https://medium.com/media/34d8a7b4e1582efcd7b9ee3eb42e3334/href</a></iframe><p>Wow, that’s not pretty. Espresso looped around 10k times and finally gave up after a minute. What can we do to circumvent this issue and tell the Espresso that the screen is actually idle?</p><h4><strong>Proposed Solutions</strong></h4><p>Let’s do a quick Google search and see what we find</p><ol><li><strong>Replace the Progressbar right after test starts</strong></li></ol><p><a href="https://stackoverflow.com/questions/33289152/progressbars-and-espresso/37864603">ProgressBars and Espresso</a></p><p>There is no accepted answer so we can start with the most upvoted one. It simply suggests that if your Progressbar is invisible at the start of the test(yes, in our case), just change its drawable with something static so it does not animate.</p><p>Although this may sound very legit and works, it doesn’t feel right to me. First of all, there is a big assumption that my test will start without showing the progressbar. When this doesn’t hold, the whole approach fails. Secondly, it requires me to mess with UI during testing. Not before, not after, but exactly at the time of running the test. This hack sounds innocent but violates some of the principles of UI testing.</p><p><strong>2. Override Progressbar for Debug builds (or for any flavor)</strong></p><p>This was the first thing that also I thought of. Create a new ProgressBar, extending from the original ProgressBar, and stop the animation in Debug builds.</p><p>I wouldn’t recommend directly doing this because debug builds are intended to be used by developers during hands on testing or development time, in which animations should not be disabled for any reason. Luckily, we have a flavor of our app that is intended for instrumentation testing. Instead of debug builds, we can disable the animations according to this flavor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/740ee745f3eb1fa634e5816b4fb160f6/href">https://medium.com/media/740ee745f3eb1fa634e5816b4fb160f6/href</a></iframe><p>Again like the first one, this approach works if you are OK with it. My concern is that changing production code and adding logic to circumvent a testing issue might cause unpredictable side-affects. Also, it’s again in violation of core principles of UI testing.</p><p><strong>3. Others</strong></p><p>As far as I checked, all the other solutions are derivatives of the first two that we have discussed. Either intercept during testing and alter the offending drawable, or change production code to account for testing. In some cases, people have given up completely and maybe stopped testing these screens.</p><p><a href="https://stackoverflow.com/a/54910497">Testing progress bar on Android with Espresso</a></p><p>In the above answer, the author suggested the use of UiAutomator. If Espresso can’t handle idleness of a progress drawable, we can simply take the control from Espresso and give it to another library with similar functionality.</p><h4>Another Possibility and Other Animated Drawables</h4><p>Until now, I haven’t even mentioned my original problem. To our bad luck, the problematical view is not even a ProgressBar or derivative of it. A custom button view that shows a Progress animation when its state switches to Loading . The drawable inside it is private so the first solution is out the window. The second solution is also out-ruled because we don’t want to interfere with production code logic.</p><p>Fortunately, there is something missing in Stackoverflow answers. Do you remember a line that 99% exists in your build.gradle file?</p><pre><em>testInstrumentationRunner </em>&quot;com.example.hello.HelloTestRunner&quot;</pre><p>This custom test runner has incredible capabilities when it comes to meddling with your app during testing. For example you can override every activity’s oncreate . There, you can utilize custom <a href="https://developer.android.com/reference/android/view/LayoutInflater.Factory">Layout Inflater Factories</a> to your liking.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a894d3788ec4399cb2692b89b9b1cc63/href">https://medium.com/media/a894d3788ec4399cb2692b89b9b1cc63/href</a></iframe><p>Now, we can just swap any view with another stub implementation that simply disables animations during testing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3e278f2fb406e58b3e4fd2354d206ef/href">https://medium.com/media/e3e278f2fb406e58b3e4fd2354d206ef/href</a></iframe><p>This method doesn’t care about your actual implementation. It can be thought of as a TestRule . When your test starts, your activities’ inflater factories are swapped with this class. The view classes that you are not interested in modifying will keep inflating as always but the ones you want to swap out will be changed with the new Stub implementations. In these stub implementations you can disable animations and do whatever you want as long as you are respecting the fundamental rules of instrumentation testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57f826102187" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/progressbar-animations-with-espresso-57f826102187">ProgressBar animations with Espresso</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[Video Player in Jetpack Compose (Part 3) — Controls and Fade Animation]]></title>
            <link>https://halilozercan.medium.com/video-player-in-jetpack-compose-part-3-controls-and-fade-animation-7952ea01510a?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/7952ea01510a</guid>
            <category><![CDATA[video-player]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 14:07:23 GMT</pubDate>
            <atom:updated>2020-08-04T14:08:04.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Video Player in Jetpack Compose (Part 3) — Controls and Fade Animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGAUXfQp2f38_YGc3JRlsQ.png" /><figcaption>Controls overlay with a simple Play/Pause button</figcaption></figure><p><a href="https://medium.com/@hllozercan/getting-started-with-jetpack-compose-dev15-abdd944de1cc">Part 1</a> ; <a href="https://itnext.io/playing-a-video-with-jetpack-compose-10a453ff956">Part 2</a></p><p>So far in this series we’ve achieved to play a video in a Composable. Through component dependencies, the video player also supported changing the source. Finally, the video player also returned media controls interface which allowed us to implement our own control buttons outside the player view. We are going to focus on adding a more sophisticated control unit in this article. Initially the plan was to also go over implementation of gestures in this article but it had changed to keep the article short and concise.</p><h3>Basic Control Buttons</h3><p>First of all, we want to include a play/pause button at the center of the video, just like popular video players from Youtube or Netflix. Of course this button will appear and disappear with a tap to video surface. To achieve this kind of layout, most basic component that we can use is Stack . This component lays out its children in Z axis. Contrary to row and column, it does not work on X-Y axes. We will use Stack to show a surface of control buttons(just play/pause for now).</p><p>Before we wrap video player surface with a Stack , we’d better start separating components with respect to their logical parts. ExoPlayer should be decoupled from UI, so we create a PlayerController which will also adopt MediaPlaybackresponsibilities. Since the controller is going to be used by many child components, we should provide it down the tree by Ambient API.</p><pre>val <em>PlayerControllerAmbient </em>= <em>ambientOf</em>&lt;PlayerController&gt; <em>{ <br>    error</em>(&quot;PlayerController is not provided for this scope.&quot;) <br><strong>}</strong></pre><pre>...</pre><pre><em>Providers</em>(<br>    <em>PlayerControllerAmbient </em>provides playerController<br>) <strong>{<br>    </strong>...<br><strong>}</strong></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08c9dd765cd85e3a07d7ac38cbef7e97/href">https://medium.com/media/08c9dd765cd85e3a07d7ac38cbef7e97/href</a></iframe><p>Let’s move AndroidView that hosts PlayerView into its own component called PlayerSurface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/825f98d2193c3b556c6445786b7c8477/href">https://medium.com/media/825f98d2193c3b556c6445786b7c8477/href</a></iframe><p>Now we are ready to use Stack to draw an overlay which will hold media control buttons.</p><pre><em>Providers</em>(<br>  <em>PlayerControllerAmbient </em>provides playerController<br>) <strong>{<br>  </strong>val controlsVisible by playerController.controlsVisible.<em>collectAsState</em>()<br>  <em>Stack</em>() <strong>{<br>    </strong><em>PlayerSurface</em>()<br>    if(controlsVisible) {<br>      <em>MediaControlButtons</em>(modifier = Modifier.<em>matchParentSize</em>())<br>    }<br>  <strong>}<br>}</strong></pre><p>We will get to MediaControlButtons in a minute but we first have to talk about how stack works and what is matchParentSize() modifier? As it is discussed earlier, Stack provides a way of putting components on top of each other in Z axis. However, horizontal and vertical layout of children of stack is configured through modifiers that exist under StackScope. These modifiers are matchParentSize and gravity .</p><ul><li><strong>gravity: </strong><em>Pull the content element to a specific [Alignment] within the [Stack].</em></li><li><strong>matchParentSize: </strong><em>Size the element to match the size of the [Stack] after all other content elements have been measured. The element using this modifier does not take part in defining the size of the [Stack]</em></li></ul><p>I’d recommend checking out <a href="https://foso.github.io/Jetpack-Compose-Playground/layout/stack/">this page</a> from Jetpack Compose Playground docs to understand how gravity modifier works. matchParentSize is not magical either. It tells the component that it is applied to: “match the size of this stack component”. Using this modifier, we will match MediaControlButtons‘s height and width to the that of PlayerSurface.</p><p>Below examples show how exactly gravity and matchParentSize work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*pOXkkRllA9OyAA9wYvhnUQ.png" /></figure><p>Let’s start adding control buttons by a simple Play/Pause toggle button. MediaControlButtons should also have a transparent dark background to present contrast between video and the overlay content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8290cd4a91d8f9b4a8e5357dff8eaf86/href">https://medium.com/media/8290cd4a91d8f9b4a8e5357dff8eaf86/href</a></iframe><p>We are again making use of stack. This time we are putting a background box to catch clicks. If the user clicks on the background of dark overlay, controls should disappear from the screen. Also, we have a separate UI component for PlayPauseButton which will be centered on controls surface.</p><p>However, our project currently does not have extended icon set from Compose. Add the following dependency to your build.gradle to have access to vast majority of Material Icons.</p><pre>implementation &quot;androidx.compose.material:material-icons-extended:$compose_version&quot;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b2a972a2dfbe09a0389808aa22f9711/href">https://medium.com/media/1b2a972a2dfbe09a0389808aa22f9711/href</a></iframe><p>There are use of non-existent functionalities in several lines. Currently, our player does not expose a state of isPlaying or playbackState . Neither it provides a playPauseToggle . Going back to the controller, a simple listener should do the trick.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fda5b7e8671312b696f7785b04c9163f/href">https://medium.com/media/fda5b7e8671312b696f7785b04c9163f/href</a></iframe><p>The visibility of MediaControlButtons must be part of the state. Introducing a boolean state in PlayerController with setter function should be enough.</p><pre>private val _controlsVisible = <em>MutableStateFlow</em>(false)<br>val controlsVisible: StateFlow&lt;Boolean&gt; = _controlsVisible<br><br>fun setControlsVisible(isVisible: Boolean) {<br>    _controlsVisible.value = isVisible<br>}</pre><p>Finally, we’ll need a clickable to show the controls when they are gone from the UI. Although we can add a clickable modifier to either root Stack or PlayerSurface , creating a separate surface that catches clicks will serve better in the future when we add gestures like dragging or double tapping.</p><pre>@Composable<br>fun SurfaceGestures(modifier: Modifier = Modifier) {<br>    val playerController = <em>PlayerControllerAmbient</em>.current<br><br>    <em>Box</em>(<br>        modifier = modifier<br>            .<em>clickable</em>(indication = null) <strong>{<br>                </strong>playerController.setControlsVisible(true)<br>            <strong>}<br>    </strong>)<br>}</pre><p>Add it to the root stack</p><pre><em>...<br>PlayerSurface</em>()<br><em>SurfaceGestures</em>(modifier = Modifier.<em>matchParentSize</em>())<br>if(controlsVisible) {<br>...</pre><p>There we have it. It took a bit of time and multiple Composable components. In the end the cornerstones were “utilizing Stack“ and “decoupling player from the UI hierarchy”.</p><h3>Animate Toggle</h3><p>For now, the toggle looks and feels raw. The answer is simple; fade animation. Our experience from all the other interactions lead us to expect some kind of transition indicator before showing or hiding the controls. Although for any fade animation, I would recommend using CrossFade composable, it does not quite work in here because this not a switch between two existing layouts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af40b4478c1520ae0ef7ed628e9ed48/href">https://medium.com/media/1af40b4478c1520ae0ef7ed628e9ed48/href</a></iframe><p>The above code is taken from a complete project so there are composables that we haven’t yet implemented. Content composable is very similar to what we currently have. The animation happens in invoke operator, which also makes this object callable and composable.</p><p>Fade animations for switching between visible and invisible states have a common pitfall; whether to remove the view from UI, if yes, when?</p><p>Let’s simplify the situation with the following;</p><ul><li>Invisible: Does not exist on UI tree</li><li>Visible: Exists on UI tree with any opacity level</li></ul><pre>Appear:<br>Invisible -&gt; Visible(alpha=0.0) -&gt; Visible(alpha=0.1) -&gt; ...<br>Visible(alpha=0.9) -&gt; Visible(alpha=1) ~ Visible</pre><pre>Disappear: Reversed Appear</pre><p>To remove a view from the tree, we must wait until the animation is complete. So we create another state for “existing”. This state depends on the actual state for visibility that is coming from the controller. When controlsVisible change to whether true or false, “existing” becomes true because we always have an animation for both appear and disappear actions.</p><p>Also, when the animation finishes, we check whether the view became visible or invisible. If it is now visible, we don’t have to do anything but if it became invisible, we have to remove it from the hierarchy. Simply add an animation listener which modifies the “existing” state.</p><pre>onStateChangeFinished = {<br>    setControlsExistOnUITree(it == VISIBLE)<br>} </pre><p>I hope this article helped you better understand UI layout and animations in Compose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7952ea01510a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing a Video with Jetpack Compose]]></title>
            <link>https://itnext.io/playing-a-video-with-jetpack-compose-10a453ff956?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a453ff956</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[players]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 08:07:44 GMT</pubDate>
            <atom:updated>2021-03-04T07:13:31.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ISNOFs1sINt-0oNQhNw-A.png" /><figcaption>BetterVideoPlayer Preview, one of my earlier projects</figcaption></figure><p>This post has been edited after Beta release of Jetpack Compose.</p><h3>Deciding on a Player</h3><p>Before we start with how to play a video in a composable view, we need to decide on a player class. It would be rather a huge undertaking to develop a player from scratch. In this project, we are only interested in UI side of things. That relieves us from individual frame rendering, remote data fetching, and state management of a classic media player.</p><p>Android’s own MediaPlayer SDK is alright for a simple Video Player project. I’ve even used it in one of my older open source projects called <a href="https://github.com/halilozercan/BetterVideoPlayer">BetterVideoPlayer</a>. However, it has quite a few problems when it comes to supporting variety of codecs, especially from remote media sources. Rather than dealing with basic MediaPlayer problems, I decided to opt-in for <a href="http://exoplayer.dev/">ExoPlayer2</a> which is used by Youtube Android App. It has its own UI module to make things even easier for us but we’re going to limit our usage to only a surface(PlayerView) that will render the video.</p><p>Add this to build.gradle dependencies on app module. I’m skipping other compose dependencies in this tutorial.</p><pre>implementation &#39;com.google.android.exoplayer:exoplayer:2.11.7&#39;</pre><p>Since we do not want to concern ourselves with managing a player at this time, we can get-away with a basic configuration to barely play a video.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee88f0830303da330594b4595bf86312/href">https://medium.com/media/ee88f0830303da330594b4595bf86312/href</a></iframe><p>Before we go further, let’s add INTERNET permission to AndroidManifest since we will be using remote sources.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h3>Inflating a Traditional View</h3><p>ExoPlayer needs a surface to render the video that it holds. However, ExoPlayer currently does not support composable functions as legitimate Android Views. It works with TextureView, SurfaceView, and ExoPlayer’s own PlayerView. The first two choices require fine graining details about position, size, and aspect ratio. Instead of trying to deal with these problems, we can go with PlayerView which works quite alright with ExoPlayer.</p><p>Then the big question comes. How are we going to render a traditional Android View in a Composable. The answer is <a href="https://joebirch.co/android/exploring-jetpack-compose-android-view/">AndroidView</a>. It has a very simple interface that works well for most use cases including ours. You can learn more about AndroidView and other interop between traditional Android and Compose in this <a href="https://developer.android.com/jetpack/compose/interop#views-in-compose">documentation</a> from Google.</p><p>We can add AndroidView that inflates a PlayerView into our composition to glue together a VideoPlayer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12790805641065492c26cca8e2544658/href">https://medium.com/media/12790805641065492c26cca8e2544658/href</a></iframe><p>When you run the application, it should play the video normally. Of course, we hadn’t add any controls for the playback, but we’ll get to that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dbhNUUWiN9axrxxcZktmw.png" /></figure><h3>Passing arguments as state</h3><p>Most of the stuff about the player is missing and what is available is hard-coded right now. We can explore all the possible features that we can work with. One possible scenario is that the user might wanna change the video source. To accomplish this, we are going to assume that the source will be provided through arguments of VideoPlayer composable.</p><p>MainActivity content should declare source as a state and define a way to modify this state. Also current state should be passed down to VideoPlayer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88c3afdc4da501e13d535b1a1b59190c/href">https://medium.com/media/88c3afdc4da501e13d535b1a1b59190c/href</a></iframe><p>VideoPlayer will make use of LaunchedEffect to catch changes in source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7404382a7e729808f714779bfaf52db4/href">https://medium.com/media/7404382a7e729808f714779bfaf52db4/href</a></iframe><p>ExoPlayer is no longer created with a hard-coded source. Instead, it utilizes LaunchedEffectto re-set the source whenever this argument changes coming into the composable function. If you run the application at this time, you will see that pressing the button changes the source of the running video instantly and nothing gets messed up. ExoPlayer retains instance as well as PlayerView itself.</p><h3>Composable functions are more than bare Views</h3><p>We have made quite a progress since we started. There is now a functioning video player in our hands with Jetpack Compose. Although it is basic, this is the start of many opportunities. From this point forward, we can fully utilize what Jetpack Compose offers us. However, there is one thing that can be addressed before moving on.</p><p>Composable functions are more than Views. They are fully functional . I cannot emphasize that enough. They can have return values. They can have random kotlin code running in the middle of a Column definition. So, composable functions can even have returns types, just like remember which is also composable. This indicates that VideoPlayer can return some kind of a controller to caller function. Let’s say that this controller is for media playback. Let’s define a simple playback control set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4cf682445e62ea9935a89f54cda639c/href">https://medium.com/media/e4cf682445e62ea9935a89f54cda639c/href</a></iframe><p>Return this interface from VideoPlayer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/240c9624c6231c19ec91954a3043de6b/href">https://medium.com/media/240c9624c6231c19ec91954a3043de6b/href</a></iframe><p>Finally add controls to the main UI</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1092033395d7117ebb51d88ab428139c/href">https://medium.com/media/1092033395d7117ebb51d88ab428139c/href</a></iframe><p>When we run the application, we can see that controls work just fine without again interfering with any other state of the whole composition.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-6w4vzHnHIY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-6w4vzHnHIY&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e5535cbfa645e5c4940833db72fe2f/href">https://medium.com/media/66e5535cbfa645e5c4940833db72fe2f/href</a></iframe><h3>Next</h3><ul><li>Add controls and gestures to the Player</li><li>Compose currently lacks a SeekBar(Slider), implement and add it to the Player</li><li>Finishing touches with some animation tricks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a453ff956" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/playing-a-video-with-jetpack-compose-10a453ff956">Playing a Video with Jetpack Compose</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Jetpack Compose (dev15)]]></title>
            <link>https://halilozercan.medium.com/getting-started-with-jetpack-compose-dev15-abdd944de1cc?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/abdd944de1cc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[players]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[vidéo]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 08:03:47 GMT</pubDate>
            <atom:updated>2020-07-29T08:08:50.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxMkOkF6ed6O43JC7ihU8Q.jpeg" /></figure><p>This write-up is divided into 5 cohesive parts for better delivery. This post is about getting into Jetpack Compose for the first time and figuring out little details before moving onto more concrete implementations with clear goals. The link for next posts can be found at the bottom.</p><h3>What is Jetpack Compose?</h3><blockquote>Jetpack Compose is a modern toolkit for building native Android UI. It’s based on the declarative programming model, so you can simply describe what your UI should look like, and Compose takes care of the rest — as app state changes, your UI automatically updates.</blockquote><p>Declarative UI frameworks took the web by storm with the introduction of React from Facebook. Virtual DOM changed the way developers think about how UI should be designed and controlled by code. Imperative methods served good over decades but they got exponentially complicated with the increasing complexity of modern products. Moreover, front-end teams started to separate with respect to their responsibilities of features. This kind of modularization required the architecture of written software to reflect the same change according to <a href="https://en.wikipedia.org/wiki/Conway%27s_law">Conway’s Law</a>. Declarative frameworks like React and Vue addressed these and other problems about modern UI. Later, they were followed by Flutter and SwiftUI both of which proved that the same paradigm can be realized on mobile phones.</p><p>Android SDK was first published in late 2000s when UI programming was still living the old days. An XML-like mark-up to define the layout which then can be modified by Controller classes like Activities and Fragments. However, their simplicity no longer holds since many UI elements are now reactive by design, observing ever changing data sources and reflecting accordingly. Writing observer callbacks for LiveData objects gets cumbersome after a while. To address these issues, Android Tools Team has undertaken a “revolutionary” project called Jetpack Compose to address the needs of modern UI for the upcoming decade. Native Android views will be inflated by Kotlin code through Composition, rather than XML definitions. To learn more about Compose, please visit <a href="https://developer.android.com/jetpack/compose">Google’s own documentation site</a>.</p><h3>Setting Up</h3><p>We are here to learn more about Compose, so let’s get started. First thing to note is that Jetpack Compose is still under heavy development. Current releases are published under “Developer Preview” tag which means that the APIs are subject to change(yes, they heavily do). Hence, Jetpack Compose is available only through Android Studio Canary channel. You’re going to have to download Android Studio 4.2 Canary release by the time of writing this article. It is subject to change because when 4.1 hits the main release channel, Compose will likely migrate to 4.3 because it will be on Canary channel.</p><p><a href="https://developer.android.com/studio/preview">Download Android Studio Canary</a></p><p>Once you’re done with download and initial setup, let’s start a new project with Compose support by following</p><p>&gt; Create new Project &gt; Empty Compose Activity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLmAheKomM-ER7qo6G7Lrg.png" /><figcaption>Select Empty Compose Activity to enable Compose support</figcaption></figure><p>In the next screen, enter whatever you like for application name and other properties which should not matter for the rest of the series. Unfortunately, Android Studio still starts a new Compose project using 0.1.0-dev13 version which is a little bit old right now. We’re going to upgrade it to dev15 but it requires some tweaking.</p><p>In the root build.gradle file, make sure the <strong>bold</strong> parts are up-to-date.</p><pre>buildscript <strong>{<br>    </strong>ext <strong>{<br>        compose_version = &#39;0.1.0-dev15&#39;</strong><br>    <strong>}<br>    ext.kotlin_version = &quot;1.4-M3&quot;</strong><br>    repositories <strong>{<br>        </strong>google()<br>        jcenter()<br>        <strong>maven { url = &quot;https://dl.bintray.com/kotlin/kotlin-eap&quot; }<br>    }<br>    </strong>dependencies <strong>{<br>        </strong>classpath &quot;com.android.tools.build:gradle:4.2.0-alpha05&quot;<br>        classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;<br>    <strong>}<br>}<br><br></strong>allprojects <strong>{<br>    </strong>repositories <strong>{<br>        </strong>google()<br>        jcenter()<br>        <strong>maven { url = &quot;https://dl.bintray.com/kotlin/kotlin-eap&quot; }<br>    }<br>}<br><br></strong>task clean(type: Delete) <strong>{<br>    </strong>delete rootProject.buildDir<br><strong>}</strong></pre><p>Go to build.gradlefile under app directory, change kotlin compiler version for Compose.</p><pre>composeOptions <strong>{<br>    </strong>kotlinCompilerExtensionVersion &quot;$<strong>{</strong>compose_version<strong>}</strong>&quot;<br>    kotlinCompilerVersion &quot;1.4.0-dev-withExperimentalGoogleExtensions-20200720&quot;<br><strong>}</strong></pre><p>and add the following to the end</p><pre>tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach <strong>{<br>    </strong>kotlinOptions <strong>{<br>        </strong>jvmTarget = &quot;1.8&quot;<br>        freeCompilerArgs += [&quot;-Xallow-jvm-ir-dependencies&quot;, &quot;-Xskip-prerelease-check&quot;]<br>    <strong>}<br>}</strong></pre><p>I wish we were ready now but Compose made quite a bit more change in dev15, most importantly the naming of Compose packages. You can find the complete list of these changes <a href="https://developer.android.com/jetpack/androidx/releases/compose#0.1.0-dev15">here</a>. Again go to build.gradle file and replace old dependencies with new ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgmRYn_0qu08IWfGMMB5sQ.png" /></figure><p>These two changes were enough on my setup</p><pre>implementation &quot;androidx.compose.foundation:foundation-layout:$compose_version&quot;<br>implementation &quot;androidx.compose.material:material:$compose_version&quot;</pre><p>Finally, run the application and you should see Hello Android! on the screen.</p><h3>State, React, Compose</h3><p>Let’s check out this initial code.</p><pre><em>setContent </em><strong>{<br>    </strong><em>ComposeTubeTheme </em><strong>{<br>        </strong>// A surface container using the &#39;background&#39; color from the theme<br>        <em>Surface</em>(color = MaterialTheme.colors.background) <strong>{<br>            </strong><em>Greeting</em>(&quot;Android&quot;)<br>        <strong>}<br>    }<br>}</strong></pre><pre>@Composable<br>fun Greeting(name: String) {<br>    <em>Text</em>(text = &quot;Hello $name!&quot;)<br>}</pre><p>Here, we can immediately see that setContentView(R.layout.activity_main) is no longer. Instead, there is a setContent extension function on Activity that takes in a @Composable lambda. This is our little rabbit hole to get into the world of Compose. From here on, under this scope, every composable function will have a chance to affect the UI.</p><p>We start with a Surface, which takes a background argument. The trailing lambda is also another Composable which will be rendered on the given Surface. This is the most basic relation that can be found in any declarative UI framework. The UI tree is now being constructed through use of content composables.</p><p>Greeting is a custom Composable that takes in an argument called name and shows a Text with the said argument. When we checkout our Tree, we have</p><p>Surface &gt; Greeting -&gt; Text</p><p>However, this page is currently completely static. There is no user interaction or outsource data that will affect how the UI looks. Let’s change that by introducing a button that should add another Hello Android! text.</p><pre><em>setContent </em><strong>{<br>    </strong><em>ComposeTubeTheme </em><strong>{<br><br>        </strong>val (count, setCount) = <em>state </em><strong>{ </strong>1 <strong>}<br><br>        </strong><em>Surface</em>(color = MaterialTheme.colors.background) <strong>{<br>            </strong><em>Column </em><strong>{<br>                </strong><em>Button</em>(onClick = <strong>{<br>                    </strong>setCount(count+1)<br>                <strong>}</strong>) <strong>{<br>                    </strong><em>Text</em>(&quot;Add&quot;)<br>                <strong>}<br>                </strong>(1..count).<em>forEach </em><strong>{<br>                    </strong><em>Greeting</em>(&quot;Android&quot;)<br>                <strong>}<br>            }<br>        }<br>    }<br>}</strong></pre><p>Wait a minute. What is state function? State is one of the building blocks of Compose. state function returns an instance of State class which has a special place in Compose compiler. Any time a state changes, its scoped Compose gets invalidated and recomposes itself. In this case, we increase the count when we click on a button. This triggers a recomposition of the whole view. I cannot go into the details of state and recomposition works in this arcitle, so you will have to read a little bit of documentation for that. While reading the documentation, I also strongly suggest looking at another foundational function and paradigm called remember .</p><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/package-summary#state">https://developer.android.com/reference/kotlin/androidx/compose/package-summary#state</a></p><h3>Composition Callbacks</h3><p>Managing the state is not an easy task. It requires many trials and errors, sometimes logging to truly understand what is going around, what is being triggered according to which changes. Compose gives us strong tools that are capable of manipulating the every pixel on the screen. Developers should be vary of manipulating state carelessly because each recomposition has a cost despite the fact that it is optimized heavily.</p><p>For that reason, main composition callbacks are worth practicing over because they let developers hook into composition lifecycle whenever necessary. Main callbacks are also listed in the documentation I linked</p><p><strong>onActive</strong></p><ul><li>The <a href="https://developer.android.com/reference/kotlin/androidx/compose/package-summary#androidx.compose$onActive(kotlin.Function1((androidx.compose.CommitScope,%20kotlin.Unit)))/callback">callback</a> will execute once initially after the first composition is applied, and then will not fire again.</li><li>onActive is called once the View is added to the Composition tree.</li></ul><p><strong>onPreCommit</strong></p><ul><li>The onPreCommit effect is a lifecycle effect that will execute <a href="https://developer.android.com/reference/kotlin/androidx/compose/package-summary#androidx.compose$onPreCommit(kotlin.Function1((androidx.compose.CommitScope,%20kotlin.Unit)))/callback">callback</a> every time the composition commits, but before those changes have been reflected on the screen</li></ul><p><strong>onCommit</strong></p><ul><li>The onCommit effect is a lifecycle effect that will execute <a href="https://developer.android.com/reference/kotlin/androidx/compose/package-summary#androidx.compose$onCommit(androidx.compose.onCommit.V1,%20androidx.compose.onCommit.V2,%20kotlin.Function1((androidx.compose.CommitScope,%20kotlin.Unit)))/callback">callback</a> every time the inputs to the effect have changed.</li><li>It is the best place to have any side-effects related to the changing inputs.</li></ul><p><strong>launchInComposition</strong></p><ul><li>Launch a suspending side effect when this composition is committed and cancel it when <a href="https://developer.android.com/reference/kotlin/androidx/compose/package-summary#launchInComposition(kotlin.coroutines.SuspendFunction1)">launchInComposition</a> leaves the composition.</li></ul><p><strong>onPreCommit, onCommit, and launchInComposition </strong>have variants which take arbitrary variables as arguments. These variants are used as a controlling unit to decide whether to invoke these callbacks. If variables haven’t been changed since the last time the callback was called, then callback does not get triggered. The inverse is also true.</p><p><strong>onDispose</strong></p><ul><li>An effect used to schedule work to be done when the effect leaves the composition.</li></ul><h3>A little experiment</h3><p>It is not an easy to task to completely understand when these callbacks are triggered or what are they useful for. They all exist for some use case. To better understand their nature, I prepared this simple app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fa36f4a537a9e6224bc97693e3e2955/href">https://medium.com/media/3fa36f4a537a9e6224bc97693e3e2955/href</a></iframe><p>After hitting the increase button two times, resulting logs are:</p><pre>onCompose remembered Counter: 0<br>launched in composition<br>onActive Counter: 0<br>onCommit Counter: 0<br>ShowTextAmbient commits<br>ShowTextAmbient2 commits<br>ShowTextAmbient3 commits<br>ShowTextRegular commits<br>ShowTextRegular2 commits<br>ShowTextRegular3 commits<br>launched in composition after 2 seconds<br>onCompose remembered Counter: 0<br>onCommit Counter: 1<br>ShowTextAmbient3 commits<br>ShowTextRegular commits<br>ShowTextRegular2 commits<br>ShowTextRegular3 commits<br>onCompose remembered Counter: 0<br>onCommit Counter: 2<br>ShowTextAmbient3 commits<br>ShowTextRegular commits<br>ShowTextRegular2 commits<br>ShowTextRegular3 commits</pre><ul><li>Remember always returns the same result from when it was first invoked.</li><li>onActive is called only once when the view is first composed</li><li>onCommit is triggered after every state change.</li><li>Ambients are convenient when you want to pass down items in a nested structure. They eliminate unnecessary composition in between.</li></ul><h3>Next</h3><ul><li><a href="https://medium.com/@hllozercan/playing-a-video-with-jetpack-compose-10a453ff956">Write a simple Video Player in Compose(one that just plays)</a></li><li>Add controls and gestures to the Player</li><li>Compose currently lacks a SeekBar(Slider), implement and add it to the Player</li><li>Finishing touches with some animation tricks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abdd944de1cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proper Incident Command Center in Android]]></title>
            <link>https://halilozercan.medium.com/proper-incident-command-center-in-android-800c9579b15?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/800c9579b15</guid>
            <category><![CDATA[opsgenie]]></category>
            <category><![CDATA[picture-in-picture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[bluetooth]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 13:20:19 GMT</pubDate>
            <atom:updated>2020-01-22T08:44:52.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*QKYZxHElUODSNB5H6IXL5A.jpeg" /></figure><p>Incidents are the times where fast and reliable communication becomes the highest priority in a team. When not just minutes but seconds matter, an easy way to reach to responders may resolve an incident in a shorter time which potentially saves a company <a href="https://kapost-files-prod.s3.amazonaws.com/published/54ef73ef2592468e25000438/idc-devops-and-the-cost-of-downtime-fortune-1000-best-practice-metrics-quantified.pdf">millions of dollars</a>. That’s why Opsgenie had introduced a feature called <a href="https://www.prnewswire.com/news-releases/opsgenie-brings-incident-collaboration-to-a-whole-new-level-with-incident-command-center-300582925.html">Incident Command Center(ICC)</a> back in January of 2018. This feature can be grossly summarized as a VoIP application with video support. Opsgenie has committed to improve and expand ICC beyond being just a quirk since its inception. ICC now supports Zoom integration on all platforms where Opsgenie is offered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywLUoRDxJ0eCF5dvM4A43g.png" /><figcaption>Incident Command Center on Web</figcaption></figure><p>Talking from a technical perspective, VoIP applications get complicated deeper you go in the development. Simply the act of transferring video in a conference session with multiple attendees requires a dedicated architecture. Thanks to Twilio, this is not a huge burden anymore for anyone who endeavors in realtime communication. Opsgenie also decided to utilize Twilio for rapid development of ICC since official SDKs were provided for Web, Android and iOS. These SDKs handle connecting to a room, receive unique identification, data tracks, audio tracks, and video tracks of participants while broadcasting the same from the local device. Nonetheless, a conferencing tool does not end here. A proper user experience goes a long way for an incident management software. Although <a href="https://github.com/twilio/video-quickstart-android">Twilio QuickStart guide</a> gave a convenient starting point for us, it did not delve into some use-cases we have needed in Android client. Here we are going to talk about our experiences in developing ICC which supports Picture-in-Picture and Bluetooth headset connections.</p><h3>Picture-in-Picture</h3><p>Although Android started supporting picture-in-picture(PiP) mode natively in Android 8 (Oreo), actually Android 7 (Nougat) brought split-screen feature which is not really different in terms of how they behave. Since its beginning, Android has been focused on being a mobile operating system meaning it did not need to support multiple windows. Maybe this could have been true at the beginning when average screen resolution was around 480 by 320 and average screen size was 3.2 inches. However, this did not hold true for long and average screen size quadrupled while resolution fluctuated in its growth due to battery consumption. In the end, it became clear that modern devices can support multiple windows where it deemed necessary. So, Android followed suit and added native PiP focused on video players, video chat, and navigation applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*O5rsX8gtwCnlarJZbuXyMA.jpeg" /><figcaption>Incident Detail Screen with ICC in Picture-in-Picture Mode</figcaption></figure><p>On the side of Opsgenie, ICC meant a crisis situation where taking actions and inspecting details must not be an obstacle. Hence, PiP became a necessity since it enabled users to browse any application while remaining in the conference.</p><p>Looking at the <a href="https://developer.android.com/guide/topics/ui/picture-in-picture">docs</a>, PiP seems really easy to adopt in any application. Only a manifest change and some lifecycle callbacks seem enough to ship a prototype.</p><p><strong>Manifest Changes:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afacd2906362871b638daeaa9287a31f/href">https://medium.com/media/afacd2906362871b638daeaa9287a31f/href</a></iframe><p><strong>Activation:</strong></p><pre>activity?.enterPictureInPictureMode()</pre><p><strong>Auto activation when user leaves:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df5280bfbc93df45109039cbd30e5442/href">https://medium.com/media/df5280bfbc93df45109039cbd30e5442/href</a></iframe><p>Of course as any Android Development Doc, this also has small issues and missing points that we would like to discuss here. Let’s start with what Picture-in-Picture actually does behind the scenes. When the code calls enterPictureInPictureMode(), if successful, system detaches calling activity from its task stack to prevent any strange behavior when the user launches a different activity from the same application (side note: a strange behavior happens not matter what).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*BY8SMSyuS9ZMgGeAQYKCVQ.png" /><figcaption>How Activity Stack behaves when PiP is initiated</figcaption></figure><p>This situation has a slight side-effect on back press action. After re-maximizing the PiPed activity, pressing <strong><em>back</em></strong> completely leaves the current application rather than going back to the previous screen since PiPed activity is now detached and living on its own stack. Moreover, when the user opens up the recents menu after leaving the application, they will see two different entries belonging to the same application which is rather unusual and confusing. Completely preventing this issue requires reattaching the activity to its old task stack which involves a <a href="https://proandroiddev.com/task-management-for-picture-in-picture-mode-on-android-o-882103271cad">confusing hack</a>. However, we found two manifest configurations that are not mentioned in official PiP guide: autoRemoveFromRecents and excludeFromRecents. Looking at their description it is really difficult differentiate them. Besides this confusion, experimenting with both also yields no difference in most situations. What we found in the end is that autoRemoveFromRecents only removes the task from recents menu when itself and its descendants are finished while excludeFromRecents completely ignores a new task in recents menu where root activity has this tag.</p><p>In short, adding autoRemoveFromRecents=“true” to activity’s manifest tag achieves the closest user experience we expect from a PiP activity. As long as this activity is finished, it does not appear in recents menu but it is still accessible while conference is on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bcab4f1ed9379c3312ead8f96a0d9e2/href">https://medium.com/media/1bcab4f1ed9379c3312ead8f96a0d9e2/href</a></iframe><p>Furthermore, official guide suggests using onUserLeaveHint to catch all the actions when user leaves the current screen. This definitely helps with Fragments in a ViewPager but misses an important action which is <strong><em>pressing back</em></strong>. For this case, we bundled the logic of starting PiP in a separate method which can be called from both onBackPressed and onUserLeaveHint. Both actions also check whether conference is started to determine whether PiP mode should be initiated. A successful initiation overrides onBackPressed and prevents the subsequent routine from killing the activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5917279039b8f83c079778db8352e201/href">https://medium.com/media/5917279039b8f83c079778db8352e201/href</a></iframe><p>Also starting PiP calls onPause and returning back calls onResume in which you should not pause any player activity or conference. Even so, it is perfectly normal to assume that when the user hits X mark on the PiP, activity should be closed. Well, not quite. In this instance, onStop is called which is definitely not a definitive indication of closure because it is also called when user goes to recents menu. The way we found whether user closed the activity from X button is to listen onPictureInPictureModeChanged.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9803e53c3568ed3774997a22348e3196/href">https://medium.com/media/9803e53c3568ed3774997a22348e3196/href</a></iframe><p>Android system calls this method whether user returns to activity from PiP or closes the PiP window. To understand the difference, we can check whether activity is still in the background when this callback is executed. This way, we properly disconnect from the conference room when user sees nothing on the screen.</p><h3>Bluetooth Headset in Communication Mode</h3><p>Something we have missed during our tests was the use of a bluetooth headset in ICC. Most users and developers may assume that the system arranges this kind of behavior by default when the system is already informed that the application is making a communication. The truth is far beyond that for Android. Anyone who is familiar with how AudioManager works should know that there is nothing guaranteed and you can only make assumptions. For example, AudioManager documentation suggests use of MODE_IN_COMMUNICATION if you are developing a VoIP app. Twilio QuickStart Guide also suggests use of this mode. However, no-one mentions that using this mode will not affect audio routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*TPFc_-SipxU_wGEkzHsfkQ.png" /><figcaption>Bringing the functionality to that mock button had been more challenging than anticipated</figcaption></figure><p>What is Audio Routing? It is simply determining where the audio is played at. An application should at least support earpiece, speaker, wired headset and bluetooth headsets. First function someone will encounter while searching for this topic is setSpeakerPhoneOn(boolean) in AudioManager. Although first experiments might show that it covers most use cases, actually it does not help at all when it comes to bluetooth. If we also think about how bluetooth headphones are becoming increasingly popular thanks to <em>true wireless</em>, supporting bluetooth headsets becomes an obligation.</p><h4>First finding</h4><p>If we actually use MODE_IN_CALL as the current mode, the bluetooth headset receives sound but remains very strict. In other words, we cannot switch back and forth when ICC is started with this mode. Hence, there is no toggle option for bluetooth. On the bright side, this is our first clue in using bluetooth.</p><h4>Is there anybody out there?</h4><p>Well, surprisingly the resources are really scarce on this subject. Actually this is one of the top reasons why we are writing this blog, to at least give hope to following developers that it is possible. Searching and analyzing tens of different resources, we have almost come up with nothing. One thing we found was something called SCO for bluetooth devices. This mode modifies the current connection between bluetooth headset and the device and initiates a call experience where bluetooth microphone is also utilized. However, again we hit a wall implementing SCO because of limited resources.</p><h4>A Light of Hope</h4><p>Next, we found this <a href="https://github.com/twilio/video-quickstart-android/issues/76">issue</a> on Github. One of the commentators shared a <a href="https://webrtc.googlesource.com/src/+/master/examples/androidapp/src/org/appspot/apprtc/AppRTCAudioManager.java">link</a> which demonstrates that maybe this issue is not easily solvable after all(!). We immediately started analyzing this code. Lo and behold it was exactly what we needed. Despite the fact that it seems convoluted, we already knew there were many edge cases that needed close attention. Adopting several classes from this sample project solved the entirety of our problems regarding bluetooth and SCO.</p><blockquote>Below code examples are heavily commented in favor of decluttering this post.</blockquote><p>In short, here are few points that developers need to know about when dealing with Bluetooth calls:</p><ul><li>Decide which devices you need to support and define them.</li></ul><pre>enum class AudioDevice {<br>    SPEAKER_PHONE, WIRED_HEADSET, EARPIECE, BLUETOOTH, NONE <br>}</pre><ul><li>Keep track of which devices are connected at the moment and which one is selected</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54044140ee409dca4520be17fa127b7/href">https://medium.com/media/b54044140ee409dca4520be17fa127b7/href</a></iframe><ul><li>Make sure you start SCO for bluetooth correctly</li></ul><pre>bluetoothState = State.SCO_CONNECTING<br>audioManager.startBluetoothSco()<br>audioManager.isBluetoothScoOn = true</pre><ul><li>Keep track of bluetooth connections</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03682ee70251094c8c60db6305ee8201/href">https://medium.com/media/03682ee70251094c8c60db6305ee8201/href</a></iframe><ul><li>An updating function which routes the audio according to current selected and available device state</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65fb5800c71f522e5acb7728988833f2/href">https://medium.com/media/65fb5800c71f522e5acb7728988833f2/href</a></iframe><p>As we said, almost all of this code was adapted from <a href="https://webrtc.googlesource.com/src/+/master/examples/androidapp/src/org/appspot/apprtc/AppRTCAudioManager.java">webrtc example of Google</a>. It is sometimes crucial to admit that some problems are hard and may require not so elegant solutions. In near future, we will try to open source a library, again inspired from this adapted code, fully written in Kotlin.</p><h3>In Conclusion</h3><p>In this post, we have not mentioned how video rendering worked and how lifecycle events were processed prior to bringing PiP feature. We only wanted to talk about some pain points and unexpected behaviors that are not easily found by a quick Google search. Although Android Development is rich in documentation and blog posts, some features are still missed and not talked in detail because they are not shared by majority of applications. Hopefully, this post helps developers who are tasked with implementing a VoIP feature and got stuck in a vicious circle of unexpected and seemingly impossible behavior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800c9579b15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Android DataBinding in CustomViews]]></title>
            <link>https://halilozercan.medium.com/using-android-databinding-in-customviews-e28cad412516?source=rss-e41a22a47844------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28cad412516</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[android-data-binding]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[bindingadapter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Halil Ozercan]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 12:26:25 GMT</pubDate>
            <atom:updated>2018-11-29T12:26:25.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>DataBinding — Less Boilerplate</h3><p>We probably all remember the old(like 4 years ago?) days of Android development when the presentation layer was merged into Activity code. We had to include code snippets like below everytime a view manipulation was needed.</p><pre>TextView mNameTextView = (TextView) findViewById(R.id.name_textview)</pre><p>These type of lines that are enforced by the framework are called boilerplate and often their number is inversely correlated with readability of the code. Good news is that this problem has been addressed for a long time. <a href="http://jakewharton.github.io/butterknife/">ButterKnife</a> might be considered the most successful 3rd party implementation of <strong>View Binding</strong> concept using annotations. However, it was mostly just view binding, managing the views and their data still resided in the presentation layer.</p><p>Now, thanks to new <a href="https://developer.android.com/topic/libraries/architecture/">Android Architecture Components</a>, we have a better way for managing our View-Model relation more reactively. One crucial part of this architecture is <a href="https://developer.android.com/topic/libraries/data-binding/">DataBinding Library</a> which enables developers to write simple links between ViewModel(optional) and Android Views only using XML attributes. You can check <a href="https://www.androidhive.info/android-working-with-databinding/"><em>this</em></a> guide to better understand how DataBinding works.</p><h3>Custom Views — Write Once, Use everywhere</h3><p>I believe it shouldn’t even be necessary to mention how useful and practical the “Custom Views” are. They comfortably pack their logic, have their own capsulated lifecycle management, offer in-depth customization and so much more. They especially come in handy while working on a rather large project.</p><p>Although using a common style among all instances of a view provides developers with easier style changes in the future, logical changes like new features cannot be handed by styling. However, extending a base view from Android Framework and having your custom view used in the project brings the possibility of managing common logic from the common base.</p><pre>class TodoListView : FrameLayout {<br>    ...<br>    fun addItem(item: TodoItem) { ... }<br>    fun removeItem(index: Int) { ... }<br>}</pre><p>Nonetheless, it can be cumbersome to write a custom view from scratch especially when it needs to support XML customizations.</p><pre>&lt;com.halilibo.todoapp.TodoListView<br>    android:id=&quot;@+id/todo_list_view&quot;<br>    android:height=&quot;wrap_content&quot;<br>    android:width=&quot;wrap_content&quot;<br>    app:removable=&quot;true&quot;<br>    app:addIcon=&quot;@drawable/ic_add&quot;<br>    app:itemStyle=&quot;@style/todo_item_style&quot;<br>    ...<br>/&gt;</pre><p>To be able to support XML customization like above, we need to add styleable attributes, parse them while initializing our view, default values when user input is absent and etc. We can get rid of all these by using DataBinding.</p><h3>Flowing DataBinding in CustomViews</h3><p>Wait, what the hell is Flowing Databinding? Well you might not be familiar with the term because I just made it up. The term comes from my frustration when I tried to google “using DataBinding in custom view for both taking data from outside and applying it inside”. Flowing DataBinding refers to the situation where a view is capable of taking data from other sources using DataBinding and also utilizes DataBinding inside to update itself. By using this approach, we can come close to almost non-boilerplate levels.</p><p>Let’s assume we are developing a Todo list application and for some reason it needs to show and manage Todo items in multiple screens inside the application. The ideal way to pass items and required configuration to the view should be like the following, “employing DataBinding”</p><pre>&lt;com.halilibo.todoapp.TodoListView<br>    android:id=&quot;@+id/todo_list_view&quot;<br>    android:height=&quot;wrap_content&quot;<br>    android:width=&quot;wrap_content&quot;<br>    app:items=&quot;{viewModel.items}&quot;<br>    app:selectedItems={viewModel.selectedItems}<br>    app:refreshing={viewModel.refreshing}<br>    app:addIcon=&quot;@drawable/ic_add&quot;<br>    app:itemStyle=&quot;@style/todo_item_style&quot;<br>    ...<br>/&gt;</pre><p>Let’s check how our TodoListView is able to read this data and pass onto its Binding</p><ul><li><strong>Create binding</strong></li></ul><pre>private val binding: LayoutTodoListViewBinding = <br>LayoutTodoListViewBinding.inflate(LayoutInflater.from(<em>context</em>), this, true)</pre><p>Above line of code can be placed directly in <strong>TodoListView.kt. </strong>It simply creates the binding and inflates the layout.</p><ul><li><strong>Prepare DataBinding ready layout</strong></li></ul><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;data&gt;<br><br>        &lt;variable<br>            name=&quot;model&quot;<br>      type=&quot;com.halilibo.todoapp.TodoListView.ObservableModel&quot; /&gt;<br><br>    &lt;/data&gt;<br><br>    &lt;merge<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;&gt;</pre><pre>        &lt;TextView <br>             android:layout_width=&quot;wrap_content&quot;<br>             android:layout_height=&quot;wrap_content&quot;<br>             android:text=&quot;@{model.title}&quot;/&gt;<br>        &lt;ProgressBar<br>             android:layout_width=&quot;wrap_content&quot;<br>             android:layout_height=&quot;wrap_content&quot;<br>             isVisible=&quot;@{model.refreshing}&quot; /&gt;</pre><pre>        &lt;RecyclerView .../&gt;<br>    &lt;/merge&gt;<br><br>&lt;/layout&gt;</pre><p>While going through this tutorial, you will see some helper functions and utilities. These exist to make our lives easier e.g. conversion of boolean to one of Android Visibility states is not something you would want to include in View logic. Instead, we can use BindingAdapters.</p><pre>@BindingAdapter(&quot;isVisible&quot;)<br>fun updateVisibility(view: View, isVisible: Boolean) {<br>    view.<em>visibility </em>= if(isVisible) View.<em>VISIBLE </em>else View.<em>GONE</em><br>}</pre><p>Also, we will be using Observables to update our bindings at the right time, meaning when we actually change their content. To do this, we can separate model part of our custom view into a BaseObservable</p><pre>class NavigationViewModel : BaseObservable() {<br><br>    @get:Bindable<br>    var refreshing by ObservableDelegate(BR.<em>refreshing</em>, false)<br><br>    @get:Bindable<br>    var title by ObservableDelegate(BR.<em>title</em>, &quot;&quot;)</pre><pre>}</pre><pre>class ObservableDelegate&lt;T&gt;(val id: Int, initialValue: T, private val onChanged: (T) -&gt; Unit = <strong>{}</strong>) {<br><br>    var value = initialValue<br><br>    operator fun getValue(self: BaseObservable, prop: KProperty&lt;*&gt;): T = value<br><br>    operator fun setValue(self: BaseObservable, prop: KProperty&lt;*&gt;, value: T) {<br>        this.value = value<br>        onChanged.invoke(value)<br>        self.notifyPropertyChanged(id)<br>    }<br><br>}</pre><p>ObservableDelegate class is again a utility class which provides us with a default value for our observable and trigger “notifyPropertyChanged” when the object is actually changed.</p><p>Now, only remaining part is adding the bridge between outside data and inside model.</p><pre>fun setRefreshing(refreshing: Boolean) {<br>    this.model.refreshing = refreshing<br>}</pre><pre>fun setTitle(title: String) {<br>    this.model.title = title<br>}</pre><p>One of the great advantages of DataBinding is that the XML field in which you put your data, automatically calls the corresponding setter function of the view e.g. app:title calls setTitle. This way, you don’t have to write styleables and additional XML values.</p><p>Finally, we can look at how data flows through our code to the final view.</p><p>First we make a request to the server and set refreshing in ViewModel of our Activity.</p><pre>viewModel.refreshing = true</pre><p>This triggers DataBinding in Activity’s XML.</p><pre>&lt;com.halilibo.todoapp.TodoListView <br>    ...<br>    app:refreshing = &quot;@{viewModel.refreshing}&quot;<br>    ...<br>/&gt;</pre><p>Corresponding setter function is called</p><pre>fun setRefreshing(refreshing: Boolean) {<br>    this.model.refreshing = refreshing<br>}</pre><p>Now, ObservableDelegate calls <strong>notifyPropertyChanged</strong> for “refreshing” because the set function is invoked. <strong>notifyPropertyChanged </strong>correctly updates our TodoListView’s already binded XML.</p><pre>&lt;ProgressBar<br>             android:layout_width=&quot;wrap_content&quot;<br>             android:layout_height=&quot;wrap_content&quot;<br>             isVisible=&quot;@{<strong>model.refreshing</strong>}&quot; /&gt;</pre><p>isVisible calls the corresponding BindingAdapter and visibility changes.</p><h3>Conclusion</h3><p>To sum up, DataBinding solves boilerplate code problem while CustomViews solve code modularity problem. Combining their powers enable us to seamlessly transfer data between our Model and View. More importantly, our application becomes more reactive which is necessary for mobile applications which regularly fetch data from remote servers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28cad412516" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>