<?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[Schibsted Tech Polska - Medium]]></title>
        <description><![CDATA[High quality software development for a family of digital consumer brands across media, online marketplaces and technology ventures. - Medium]]></description>
        <link>https://medium.com/schibsted-tech-polska?source=rss----dc5f2a4b4e48---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Schibsted Tech Polska - Medium</title>
            <link>https://medium.com/schibsted-tech-polska?source=rss----dc5f2a4b4e48---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:39:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/schibsted-tech-polska" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When the keyboard meets Coroutines]]></title>
            <link>https://medium.com/schibsted-tech-polska/when-the-keyboard-meets-coroutines-9b09c0b159e1?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b09c0b159e1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 12:41:34 GMT</pubDate>
            <atom:updated>2020-07-16T12:41:34.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BE4nvebSRxSY2M_DEC0udQ.png" /></figure><p>The keyboard management is one of the biggest problems of the Android platform since API 1. That was almost 12 years ago. However, there are mentions of a very promising API on the horizon. In Android 11, most probably, we will finally get the control of the Soft Input Keyboard. The SDK level 30 is right now in a beta stage (July 2020) and there is currently no evidence that these functions will work on older SDKs. You can wait for a support library, that will probably be in the alpha stage for some time, or you can check what are the other options to tame the beast.</p><h3>View Tree Observer</h3><p>The most popular way to check if the keyboard is visible to a user (since 2012), is checking the difference in height in your root view. This works nicely, but introduce some magic numbers.</p><p>Is 200dp hight difference is enough to know the keyboard is here, or maybe it should be 100dp or 300dp?</p><h3>OnLayoutChangeListener</h3><p>There is another way to check the difference in height of your view. The OnLayoutChangeListener. This interface is a part of View class, so it can be attached to any class that inherits from it. Let&#39;s see some code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e36174d196795aba0e2d8bb7e7466a7/href">https://medium.com/media/2e36174d196795aba0e2d8bb7e7466a7/href</a></iframe><p>The onLayoutChange function has 9 different parameters, the view itself and 8 parameters describing the view ends, before and after the layout changes.</p><p>This function works very similarly to the ViewTreeObserver, however, it is simple to understand and simple to use. Also, what is important for a purpose of this article, is simple to wrap with coroutine. Check it out!</p><h3>Suspend Cancellable Coroutine</h3><p>Coroutines offer a way to write asynchronous non-blocking code in a sequential matter. It eliminates the need for listeners and callbacks, where a lot of nesting and decentralization might make your code unreadable and hard to understand.</p><p>The suspendableCancellableCoroutine gives us a great opportunity to give our listeners a second life.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ef14844778e0fbffd4db05d92188566/href">https://medium.com/media/8ef14844778e0fbffd4db05d92188566/href</a></iframe><p>Explanation of concept:</p><ul><li>suspendCoroutine is a function that suspends the execution of the coroutine and Cancellable gives us the ability to react upon cancellation</li><li>remove the listener. After onLayoutChange will be called, we are removing the listener to do not observe the view anymore, and to do not leak the coroutine</li><li>cont.resume, we are waking up our coroutine from suspension and resume the continuation</li><li>cont.invokeOnCancellation, as mentioned above, using <em>suspendCancellableCoroutine</em> we have a chance to react upon cancellation. In this case, we will remove the listener to do not leak the coroutine.</li><li>addOnLayoutChangeListener, last but not least, we are registering our listener for a given view</li></ul><p>The described function will be resumed after the view size change. We should focus on the reduction in Y direction only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfde4bf6012f6f29a5ac0c494250529/href">https://medium.com/media/1bfde4bf6012f6f29a5ac0c494250529/href</a></iframe><h3>Usecase</h3><p>Now, let’s think about the use case. When the keyboard opens, the available space in our app shrinks. In my opinion, that results in many use cases that UI needs to challenge. Knowing exactly when the keyboard appears, we can rearrange our view, start some animation, etc. Check the below pseudo-code for some inspiration</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f44817d7ad640ab613925abac0c4d38/href">https://medium.com/media/2f44817d7ad640ab613925abac0c4d38/href</a></iframe><p>I am using this function to synchronize views animations together with a motion layout. With the help of coroutines, the animation looks smooth and I can easily control every step of the animation.</p><p>Lately, I was working with a keyboard opening and GIF container animation in the chat app. You can check the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b6815182ee50381f0e648860d8a34ca/href">https://medium.com/media/6b6815182ee50381f0e648860d8a34ca/href</a></iframe><p>In my opinion, it is very legible. You can read it like a book and understand each step. There is one fragment to which additional attention should be paid, the one with a timeout:</p><pre>withTimeoutOrNull(VIEW_HEIGHT_REDUCTION_TIMEOUT) <strong>{<br>    </strong>binding.messagesRV.awaitsLayoutReductionInY()<br><strong>}</strong></pre><p>The function withTimeoutOrNull, runs a given suspending block of code inside a coroutine with a specified timeout and returns null if this timeout was exceeded. I found it very useful when it comes to animations. Sometimes the Android system can hang a bit or freeze without any particular reason. In those cases, your function will finish execution.</p><h3>One of the keyboard animation used in GoodOnes app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*I4-X-AOVQlWbpWpk-QS3iw.gif" /><figcaption>Gif about giphy :)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b09c0b159e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/when-the-keyboard-meets-coroutines-9b09c0b159e1">When the keyboard meets Coroutines</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robust news feeds using child view controllers in Swift]]></title>
            <link>https://medium.com/schibsted-tech-polska/robust-news-feeds-using-child-view-controllers-in-swift-a32f6eaf35eb?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/a32f6eaf35eb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[schibsted]]></category>
            <category><![CDATA[news-apps]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Marcin Mucha]]></dc:creator>
            <pubDate>Tue, 05 May 2020 10:36:23 GMT</pubDate>
            <atom:updated>2020-05-05T10:36:23.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BxQRO958Cb3bMekPIuPPw.png" /></figure><p><strong>You open your favourite news app and start reading. What makes you stay there for longer? A front page! If an interesting teaser catches your eyes, it’s more likely you will enter an article to read more.</strong></p><p>A front-page is the most important part of news apps and websites, just as it has been with classic newspapers. A group of editors and journalists work constantly to provide the best reading experience. Not only people are involved in this process, but also special algorithms and AI do their job to serve tailored content for users. It’s not only about the front page though, there are also section listings that present teasers from one specific category.</p><p>From the presentation layer perspective e.g. iOS app, a section is a similar concept to a front-page: the goal is to present a list of teasers with a given layout and allow navigation to a corresponding article on tapping them.</p><h3>Sounds easy, but could be challenging sometimes…</h3><p>In the Core News Product App team, we are developing mobile apps for several news publishers from Norway and Sweden. In the moment of writing, we have 7 apps in App Store:</p><p>Norway: Aftenposten, Stavanger Aftenblad, Fædrelandsvennen, Bergens Tidende, Verdens Gang</p><p>Sweden: Aftonbladet, Sportbladet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11ib5LL87MMZeKCyp97Wtw.png" /><figcaption>Front page and economy section in <strong>Aftonbladet</strong> iOS app.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyz_5Gqxit-ml9y4Si5scg.png" /><figcaption>Front page, VG+, and Sport sections in <strong>VG</strong> iOS app.</figcaption></figure><p>The main principle for our team is to share as much code as possible. Instead of writing 7 very similar apps, most of the code is put in the core module, which serves as a base for every app we have. Having a shared codebase and dealing with requirements that often are different among publishers is the most tricky part of our job. Imagine you have seven front pages and more than a hundred section listings counting all the apps. Here are the challenges we face every day:</p><h4>Backend aspect, presentational API:</h4><p>In Schibsted, we have a main backend service shared among publishers that apps communicate directly with. However, this is not the case for every feed. There are some feeds that differ in a data format. Some of them are consumed from custom or legacy endpoints. That means the architecture needs to be flexible enough to present basically any data that can be resolved to article teasers.</p><h4>Native vs. web content</h4><p>Most of the feeds in our apps are natively rendered but there are some exceptions. If a publisher needs to render one of the feeds in a webview, we need to handle that. What is more, some feeds require to be dynamically switched between native and web versions based on current newsroom decisions. That means even more complex behaviour.</p><h4>Feeds are not a simple list</h4><p>We can’t forget about the rest of components a typical news feed contains:</p><ul><li>advertisements</li><li>carousel or list widget (list of teasers embedded into a widget)</li><li>location aware widget (weather forecast, local news)</li><li>web rendered teasers</li></ul><h4>Common states</h4><p>Every feed has the same possible states:</p><ul><li>loading, an activity indicator is shown</li><li>presenting content</li><li>error, showing error message to user and giving the chance to retry by tapping a button</li></ul><h4>Different brands, different styling</h4><p>Having 7 different brands onboard requires seven different stylings. Besides each app having its own look, teasers have different layouts, usually resembling classic newspapers. In general, styling is a too large topic to cover in this article. What you will see is a simplification that focuses only on architectural aspects.</p><h3>Feed loading abstraction</h3><p>The goal of the blogpost is to present an architectural concept of a reusable container view controller that serves all feeds and deals with mentioned challenges.</p><p>The concept consist of two main parts:</p><ul><li>an abstraction of the loading process that allows to deal with different data formats and helps to determine what type of content is needed to load</li><li>a container view controller and its child view controllers presenting a current state of the feed</li></ul><p>I will focus on the architectural part. Therefore, I’ll simplify data models, UI part, and networking logic to focus on the core of the issue here.</p><h4>Model</h4><p>Let’s start by defining a model for a single element in the native feed. A list might contain elements of different types such as various article teaser types, several ad types, and widgets that can include teasers or location-based news. To reflect that, let’s use an enum with three simple cases. Of course, in the real app this model would be substantially more complex.</p><p>Let’s create a new enum and call it FeedItem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cadb84a160be69944b67730790d807/href">https://medium.com/media/20cadb84a160be69944b67730790d807/href</a></iframe><p>Now, we need a type that describes a feed page. As you remember, feed can be rendered natively or web-rendered. Sounds like another enum. There could be some additional pieces of information that are shared and don’t depend on a specific way of rendering. It could be a title of the feed, tracking and styling properties, or basically any metadata connected to the feed. Let’s use a title as an example of such data.</p><p>Let’s create a struct Feedthat includes those requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bdf37df9286c43db39a9fed1c52e14c/href">https://medium.com/media/3bdf37df9286c43db39a9fed1c52e14c/href</a></iframe><p>Again, we leverage the usage of enum. For native feeds, we need to hold an array of feed items. If a feed is web-rendered, we need the URL of the webpage. In both cases, a feed might have a title if it’s a section listing. The title will be then shown in a navigation bar.</p><p>As we’re done with the basic model types, let’s move further.</p><h4>How to load all the things possible?</h4><p>As I said, there is no single specific data format for every feed in our apps. Newsroom content APIs and their format are evolving and changing over the years. Remember that our apps serve 7 different Schibsted newspapers. While most feeds are consumed in a unified format, some sections still use legacy endpoints.</p><p>Besides that there are also feeds that are always web rendered and feeds that are rendered based on the flag in the response that tells whether to render natively or fallback to web. For those reasons, we need an abstraction that allows us to load feeds in a flexible way and pass information how to render it.</p><p>Let’s define a protocol that will describe that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e21a739de9ac00b49735b9c461b357e/href">https://medium.com/media/2e21a739de9ac00b49735b9c461b357e/href</a></iframe><p>Protocol consists of a function that returns AnyPublisherfrom Combine framework. For those who are not familiar with it, check out the docs: <a href="https://developer.apple.com/documentation/combine/anypublisher">https://developer.apple.com/documentation/combine/anypublisher</a></p><p>Since loading is an asynchronous process, function needs also return a value in an asynchronous manner. Feed includes information about the content, so we’re good in that aspect. Loading is a process that can fail, so we specify Error type as a failure type.</p><p>Now, let’s move on to the specific usage of the created protocol, based on the real challenges we faced during development. Imagine we have three feed pages that we would like to load in the app:</p><ul><li>Economy section from service X. It represents economic article teasers and it has its own data structure that includes everything that we need including ads and widgets. This feed can be rendered only natively.</li><li>Lifestyle section from service Y. It contains lifestyle and nutrition related teasers. This time, however, data structure is different from economy feed and it doesn’t include any information about ads or widgets. They need to be injected client-side. This feed is to be rendered natively or as a website depending on renderAsWebboolean value.</li><li>Sport section from service Z. It contains sport teasers which can be only web rendered.</li></ul><p>Let’s deal with each of them one by one. Our goal at this point is to create loaders that are able to load mentioned sections. They will be key things to use at the later point.</p><h4>Economy section</h4><p>First of all, let’s examine the data structure of the economy section. As mentioned, it includes teasers, ads, and widgets. Here’s a sample idea what a response might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9ba8570925b8e42c9c84276c8d735b0/href">https://medium.com/media/a9ba8570925b8e42c9c84276c8d735b0/href</a></iframe><p>We need to define a decodable struct that will be used to parse the response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9770904e978f24df971e4ca714dfae00/href">https://medium.com/media/9770904e978f24df971e4ca714dfae00/href</a></iframe><p>One tricky thing here is that items array is a heterogeneous collection. As you can see in the JSON file, it can be a teaser, an ad, or a widget. That means, it will be the best to define an item as an enum.</p><p>Unfortunately, Swift cannot automatically synthesize the implementation of Decodablefor such enum. It means that it needs to be implemented manually. I will not go into details here, you can check out all of the source code by entering the link posted at the end of this article.</p><p>Now, it’s time to conform to FeedLoadable protocol. Let’s create a struct called EconomyLoader.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/900b8ff8fc56b46fab615f241149d0d2/href">https://medium.com/media/900b8ff8fc56b46fab615f241149d0d2/href</a></iframe><p>As you can see, we transform an economy feed page to Feed. As requirement says, this feed is always natively rendered. To make things simple, response is loaded from a locally stored JSON file instead of requesting a real service.</p><p>Now, we need to follow similar steps for two more sections keeping their requirements in mind.</p><h4>Lifestyle section</h4><p>This time the section has a different data structure that contains no ads or widgets. However, we still want to show them at some predefined spots in the feed. For that reason, we’ll need to inject additional items client-side. Even more interestingly, the section needs to be natively or web rendered according to the renderAsWebflag in the response. Based on its value, a proper Feedobject will be created.</p><p>As before, let’s start with the page model. Checkout the JSON file of the sample lifestyle section response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b57732e17e966e89b247981cda706bd/href">https://medium.com/media/0b57732e17e966e89b247981cda706bd/href</a></iframe><p>As no manual decoding is needed in this case, the model struct is simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59bd8c610cc01d0c72bc5cfd6148db1f/href">https://medium.com/media/59bd8c610cc01d0c72bc5cfd6148db1f/href</a></iframe><p>The only new things are two properties renderAsWeband renderAsWebUrl. We will make use of these during the loading process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72c99c42538e6b2fb9ac5a2bd047cf7c/href">https://medium.com/media/72c99c42538e6b2fb9ac5a2bd047cf7c/href</a></iframe><p>As you now see, the enum Feedshows its power. This time we don’t hardcode the specific case. We can dynamically choose whether our feed will be rendered natively or web.</p><p>However, we still have one more requirement to meet. We want to inject ads and widgets. Loader’s responsibility is to deliver a final model to the view model. It will be the best approach to make any additional changes here, in loader.</p><p>We also need to remember that we live in a reality of several newspapers where the code is shared among apps. Thus, we need to be flexible here and cannot simply inject ads and widget at hardcoded indices. Each newspaper wants to have different types of ads in different places in the feed and some of them may or may not want to have widgets there. For that reason, we need to pass information about additional elements from outside by adding a new closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/935e02c17bb3a0ceff879764fdf9b033/href">https://medium.com/media/935e02c17bb3a0ceff879764fdf9b033/href</a></iframe><p>Closure transformallows us to transform FeedItem array into a new one. This way, we can do any operation on collection we want for any publisher. Of course, this applies only to a natively rendered feed. If it’s to be web rendered, we don’t do any transformations.</p><p>Let’s move on to the last and easiest section - sport.</p><h4>Sport section</h4><p>In this case, the section is always web-rendered and we know it upfront. It means we don’t need to deal with any parsing or transformations. We just need a simple loader that can return Feedwith web content for a given url. Because of that, let’s give it a generic name WebLoader.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c254cb6d5d750289bc194aa555b4144/href">https://medium.com/media/4c254cb6d5d750289bc194aa555b4144/href</a></iframe><p>In this case, what load method does s simply returning immediately with a success value of Feedwith a web content. As you can see, the WebLoader is not coupled with any particular section, it can be used for any web feed.</p><p>Now, we’re done with all three loaders and it’s time to move on to the second part of our feed architecture.</p><h3>Custom Container View Controller</h3><p>Loaders alone have no purpose. We need a way to plug them into a view controller. The goal is to implement a custom container view controller, but let me draw a bigger picture here.</p><p>As Apple documentation states:</p><p>Container view controllers are a way to combine the content from multiple view controllers into a single user interface.</p><p>What are multiple view controllers in our case? Let’s think of states a feed can have:</p><ul><li>loading</li><li>presenting native content</li><li>presenting web content</li><li>error</li></ul><p>By translate these into Swift by creating an enum State:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e08200271d4dae43b23c9bfac3762e0/href">https://medium.com/media/1e08200271d4dae43b23c9bfac3762e0/href</a></iframe><p>What’s interesting here is by using an associated value of type Feed we can nicely hold information about a type of the feed that is currently presented in the feed.</p><h4>View model</h4><p>According to MVVM principles, we’d like to scope down any business logic in the view controllers. Let’s create a FeedViewModeland make it responsible for computing the current state of the feed. How to achieve that? By using loaders from the recent chapter!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d20345e9327cbda9acd8bd19cfedd251/href">https://medium.com/media/d20345e9327cbda9acd8bd19cfedd251/href</a></iframe><p>State is defined as CurrentValueSubject&lt;State, Never&gt;. It’s a Combine type that allows us to store a single value and communicate any changes to subscribers. You can read about it more here: <a href="https://developer.apple.com/documentation/combine/currentvaluesubject">https://developer.apple.com/documentation/combine/currentvaluesubject</a>.</p><p>We used State and Never as Output and Failure types because we want to store Statevalue and we never want it to error out as we handle errors in one of enum cases.</p><p>As you see, we inject loaders in init. By using a protocol FeedLoadablewe can inject any loader we want and our FeedViewModelstill remains the same! Let’s use the loader to implement the load method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbdbad38d403c7628d0008870154bd18/href">https://medium.com/media/bbdbad38d403c7628d0008870154bd18/href</a></iframe><p>What we do here, we simply ask a loader to load a feed and we translate a result to the corresponding state. We don’t really care what type of feed it is at this point, because the view model’s responsibility is only to expose a current state to the view controller.</p><p>Let’s see the full view model code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/127c2821ce4c56c30db0fcab6d6f51ca/href">https://medium.com/media/127c2821ce4c56c30db0fcab6d6f51ca/href</a></iframe><p>Additionally, by conforming to the FeedViewModelType protocol, we make the code testable.</p><h3>Child view controllers</h3><p>Now, let’s prepare the remaining parts for our container view controller.</p><p>As mentioned before, a current state will be represented by using different view controllers. Here are suggested names:</p><ul><li>loading -&gt; LoadingViewController</li><li>presenting native feed -&gt; NativeFeedViewController</li><li>presenting web feed -&gt; WebFeedViewController</li><li>error -&gt; ErrorViewController</li></ul><p>The idea is to add a view controller corresponding to the current state as a child view controller of our container view controller.</p><p>Let’s start building our container view controller and call it FeedViewController. First, we need a property that holds current child view controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d572781c7c60b6a71c936d3277ab40/href">https://medium.com/media/b4d572781c7c60b6a71c936d3277ab40/href</a></iframe><p>By using didSet observer, we can swap child view controllers in a convenient way. How to implement updateChildren? We need to remember about a few steps when adding and removing a child view controller.</p><h4>Adding child view controller</h4><p>Let’s create an extension to UIViewController to show what needs to be done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/269c8f17512d61573ee1e89af4b59617/href">https://medium.com/media/269c8f17512d61573ee1e89af4b59617/href</a></iframe><ol><li>Method addChild creates a parent-child relationship between two view controllers which is necessary for a custom container view controller. This method tells UIKit that your container view controller is now managing the view of the child view controller.</li><li>We add the child’s view as a subview of the container’s view.</li><li>didMove(toParent:)method is required to inform the child that it has a parent view controller now.</li></ol><h4>Removing child view controller</h4><p>By analogy, let’s examine the process of removing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a7b9b4bb4b90a52fbb9697c1f6917f/href">https://medium.com/media/62a7b9b4bb4b90a52fbb9697c1f6917f/href</a></iframe><ol><li>We tell UIKit that the view controller loses its parent.</li><li>We remove the child from its parent.</li><li>Child’s view is unlinked from the superview’s view.</li></ol><p>With these extensions, updateChildrenmethod becomes really simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7490a8d6381d97e0cdf9bc4abf8daca/href">https://medium.com/media/f7490a8d6381d97e0cdf9bc4abf8daca/href</a></iframe><p>After checking if the new child is not the old child, we simply remove the old one and add the new one if it’s not nil. By creating helpers add(_ child:) and remove(), UIKit internal logic was hidden and code became readable and easy. Last thing we need to do is to position the new child’s view. In this case, we pin it to super view using auto-layout.</p><p>As we already know how to swap child view controllers, let’s move to the last part: observing FeedViewModel’s state by FeedViewController.</p><h4>Reacting to state changes</h4><p>Now, we need to ensure that every state change is reflected by adding a proper child view controller and removing old one. Since we use CurrentValueSubject this job is easy. Let’s subscribe to changes in viewDidLoad:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d59a3aa33de3ded577e571ddf5345dd/href">https://medium.com/media/6d59a3aa33de3ded577e571ddf5345dd/href</a></iframe><p>As we deal with UIKit code when adding child view controllers, we need to be sure that it’s done on the main thread. We can do it by calling .receive(on: DispatchQueue.main)just before .sink. Also, we don’t need to be worried about subscription erroring out and terminating because Failure type of state subject was set to Never.</p><p>Finally, let’s configure current child view controller based on feed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c3fae48b38e84fb3e4686607c152652/href">https://medium.com/media/1c3fae48b38e84fb3e4686607c152652/href</a></iframe><p>By using an enum for FeedViewModel.State, we have a nice, readable and predictable code. Every time state changes, the change is reflected in FeedViewController.</p><p>It’s likely that you feel now that this code might be shared among different newspapers and feeds. If a new publisher comes in, we just can just use one of existing loaders or create a new custom one, without a need to recreate the whole view controller and view model machinery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*TLKBJAdWyfGa4WtDgMe-oQ.gif" /><figcaption>Economy section</figcaption></figure><p>In case of lifestyle section, in order to simulate renderAsWeb changing across responses, I used Bool.random() to compute its value. This way we can see that the feed nicely respects it and renders natively or web depending on the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*Ek1mVqtqTM58G2P0gXbnhA.gif" /><figcaption>Lifestyle section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*sgSEf-34LsK6jD8_dTgKcg.gif" /><figcaption>Sport section</figcaption></figure><p>If you’re interested in full implementation I invite you to check out the whole sample project: <a href="https://github.com/marcin-mucha/RobustFeeds">https://github.com/marcin-mucha/RobustFeeds</a></p><h3>Conclusion</h3><p>First of all, thanks for the long journey!</p><p>You’ve learned some of the specifics of the news apps. And you’ve found out that a list of teasers you see in your favourite app might be a little bit tricky under the hood.</p><p>By using a real project use case, I wanted to show you a bigger picture of challenges we face in our everyday work. You saw how to create an abstraction over loading process with unspecified data structure and how to present such data to the user by using a custom container view controller. I’m sure that at least some parts of the sample project can be useful also in your apps.</p><p>P.S. Credits to all <strong>CNP App iOS</strong> team members for collaboration to this solution in our apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a32f6eaf35eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/robust-news-feeds-using-child-view-controllers-in-swift-a32f6eaf35eb">Robust news feeds using child view controllers in Swift</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication of Fragments in the Fragment, using Navigation Component, MVVM and Koin]]></title>
            <link>https://medium.com/schibsted-tech-polska/communication-of-fragments-in-the-fragment-using-navigation-component-mvvm-and-koin-ca9a70bf001b?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/ca9a70bf001b</guid>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 13:34:37 GMT</pubDate>
            <atom:updated>2020-04-24T21:44:30.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LZj14rhgPN37AKlhvRBgg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jordanmadrid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jordan Madrid</a> on <a href="https://unsplash.com/s/photos/compass?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Good in-app navigation is essential for the user experience. As is the flexibility that allows you to program to the new requirements. By introducing Navigation Component in Android Jetpack, Google showed a straight way to maintain the flow of our app from a central location.</p><p>In this article, I will show you how to use nested fragments in Navigation with additional help from Koin to provide the same instance of ViewModel across different destinations.</p><h3>The setup</h3><p>We are going to follow the single activity navigation pattern recommended by Google (<a href="https://www.youtube.com/watch?v=2k8x8V77CrU">link</a>). For this activity, let’s set 3 different fragments and name them One, Two and Three.</p><p>Fragment Three will hold additionally 2 other fragments named X and Y. <br>Just like on the sketch below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*X72kyqQmaoDTyjLIfjHZTQ.png" /></figure><h3>Navigation Host</h3><p>Navigation used in the navigation component is done with <a href="https://developer.android.com/reference/androidx/navigation/fragment/NavHostFragment">Nav Host Fragment</a>.</p><blockquote>NavHostFragment provides an area within your layout for self-contained navigation to occur.</blockquote><p>This means the above schema is not entirely correct. We are missing very important pieces, which are NavHostFragments. NavHost can be attached to Activity or Fragment and since it is a Fragment container, it has its lifecycle.</p><p>More about that in the next part of the article. Let’s see the updated schema for our navigation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*EFBxu9NSUlLWG3dZcCZvng.png" /></figure><h3>Navigation Host Scope</h3><p>As mentioned earlier, the NavHost is a fragment container and hence, it has its lifecycle. The creation of NavHostFragment requires a view, so the lifecycle functions where NavHostFragment can be created or called are as follows:</p><ul><li>onCreate() for an Activity</li><li>onActivityCreated() for Fragments</li></ul><p>Let’s have a look at some code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c1b5572882c03699912a25f58c1bae8/href">https://medium.com/media/3c1b5572882c03699912a25f58c1bae8/href</a></iframe><p>We do not need to specify any additional information in Activity class since this NavHostFragment(with associated NavController) is the default one, whenever we want to call it, we can use: findNavController(). The Navigation Component Library will check if any nav controller is associated with this view. If there is no NavHostFragment to which we could refer, the IllegalStateException will be thrown.</p><p>The creation looks a bit different for a fragment that is already a part of Navigation within the default(parent) NavController. We need to specify explicitly which fragment will be used as HostFragment. Apart from that, we also need to add the &lt;fragment/&gt; to the view. This time, we set the variable: defaultNavHost to <strong><em>false.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27afbdb1276cadd8e299efaed3338b23/href">https://medium.com/media/27afbdb1276cadd8e299efaed3338b23/href</a></iframe><p>As you can see on the above snippet, to find the proper fragment, we are using <em>childFragmentManager.</em></p><p>Now, whenever we would like to use it in fragments <strong>X</strong> or <strong>Y</strong>, we will just call a findNavController(). This will return navController associated with nested NavHostFragment(created in fragment Three). It works, because fragments X and Y are created within Fragment Three. Those, cannot refer to the main navController, cause it operates in different scope. Ok, so how to use it? Let me explain in the next paragraph.</p><h3>Beyond the Scope</h3><p>We have already determined that the nested fragment(child) cannot directly refer to the activity navHostFragment. Which Fragment can? All the Fragments that are included in the main navigation graph(navHostFragment). To avoid confusion I marked those with a red rectangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*YAUzwbOtqM7HtCrjOFjibQ.png" /></figure><p>We are interested in fragment Three, which is part of the main navigation and a starter point of nested navigation. We will call requireParentFragment from the fragment X to access fragment <strong>Three</strong>. RequireParentFragment r<em>eturns the parent Fragment containing this Fragment.</em></p><pre><em>val </em>fragmentThree = requireParentFragment().requireParentFragment() <em>as </em>ThreeFragment</pre><p>As you can see, we are calling it twice, because NavHostFragment is a fragment too. This is essential for providing one ViewModel for all child fragments that are in the scope of parent fragment as well.</p><h3>One (ViewModel) to rule them all</h3><p>Consider the following use case: two child fragments (as shown in the example above) communicate with each other to display some data and a parent fragment that manages their visibility based on this data. Using <a href="https://developer.android.com/jetpack/docs/guide">Google&#39;s recommended architecture</a>, we can use ViewModel for app logic. This raises a problem of the definition of the scope for that ViewModel.</p><p>At first, I thought it would not be difficult. All you have to do is initialize the ViewModel in the scope of NavHost Fragment. Unfortunately, this is not the case. To share an instance of ViewModel for parent and child fragments, we need to set the scope to parent fragment (Three), not NavHost, cause <em>Three </em>is a parent for the NavHost. How to do it?</p><ul><li>Using ViewModelProvider</li></ul><blockquote>Disclaimer: ViewModelProviders is currently deprecated, as for fragment:2.2.0</blockquote><p>We can use the constructor for ViewModelProvider() and pass ViewModelStore as a parameter. ViewModelStore is an object that manages the current state of ViewModel. More about it, <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModelStore">here</a>.</p><pre>ViewModelProvider(requireParentFragment().requireParentFragment())<br>    .get(ParentViewModel::<em>class</em>.<em>java</em>)</pre><ul><li>Using <em>by viewmodels()</em></li></ul><p>Property delegate from the library: androidx.fragment:fragment-ktx:1.2.4. It creates ViewModel lazy and scopes it to <em>this </em>Fragment by default. The default scope may be overridden with parameter: ownerProducer.</p><pre><em>val </em>viewModel <em>by viewModels</em>&lt;ParentViewModel&gt;(ownerProducer = <strong>{ </strong>requireParentFragment().requireParentFragment() <strong>}</strong>)</pre><ul><li>Using by sharedViewModel() from <a href="https://insert-koin.io/">Koin library</a></li></ul><p>This is also a property delegate that provides the ViewModel lazily. The default scope may be overridden with parameter: from.</p><pre><em>val </em>viewModel: ParentViewModel <em>by sharedViewModel</em>(from = <strong>{ </strong>requireParentFragment().requireParentFragment() <strong>}</strong>)</pre><p>That’s all. If you want to use the same instance of viewModel in a few fragments, define the scope properly and you are ready to go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca9a70bf001b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/communication-of-fragments-in-the-fragment-using-navigation-component-mvvm-and-koin-ca9a70bf001b">Communication of Fragments in the Fragment, using Navigation Component, MVVM and Koin</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Motion Layout in RecyclerView]]></title>
            <link>https://medium.com/schibsted-tech-polska/use-motion-layout-in-recyclerview-a5a3838fe6b6?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5a3838fe6b6</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 13:05:44 GMT</pubDate>
            <atom:updated>2020-01-10T09:23:46.635Z</atom:updated>
            <content:encoded><![CDATA[<p>Motion Layout is a powerful tool that helps you manage motion and animation in your app. To learn more about it, hit to the <a href="https://developer.android.com/training/constraint-layout/motionlayout">official docs</a> and/or check the series of articles by <a href="https://medium.com/u/c006d5238349">Nicolas Roard</a>. In this article I will focus on how to set nice swipe animation in RecyclerView item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*FEK4IiiODD23IZcGVQBs6Q.png" /></figure><p>TL;DR —below is the result. The code can be found on <a href="https://github.com/PiotrPrus/MotionLayoutPlayground">github</a>, scene 13.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*xiCE7VsX6Ia451g9eDpRdg.gif" /><figcaption>Swipe like/dislike in RecyclerView</figcaption></figure><h3>Preparing XMLs</h3><p>To create animations using ML we need two XML files, the one that defines layout and the other one that defines motion scene. To animate RV item, the motion layout needs to be placed in xml that defines item view. For simplicity of this example, here is the layout file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b78da638680410edb24fef348332387/href">https://medium.com/media/0b78da638680410edb24fef348332387/href</a></iframe><p>Now let’s take the second file to the workshop. Motion Scene, starting from rest/idle state of the card.</p><p><strong>State: Rest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21dd9a6f919fbad1e585820af2133703/href">https://medium.com/media/21dd9a6f919fbad1e585820af2133703/href</a></iframe><p>I will only describe states and transitions that affect the like animation. Dislike is mirror image of Like. All of the above are probably known and self explanatory, but I would like to focus on two of the constraints. <strong>layout_constraintWidth_percent</strong> and <strong>layout_constraintHeight_percent</strong> — these will set the dimensions as percent of the parent view. This is important, due to the fact that if we will constraint all four sides of view, there won’t be a room for a transition. The view would stay in place. Using a percent constraint, we are able to move the card.</p><p><strong>State: Like</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1da3f5c3ddab5daea8134b6605578b12/href">https://medium.com/media/1da3f5c3ddab5daea8134b6605578b12/href</a></iframe><p>The deriveConstraintsFrom works for the width, height and other parameters, but not for the layout_constraint. For the end of a swipe-like the view will rotate by 45 degrees and move by 300dp towards. Now we need a transition node to connect between those two states.</p><p><strong>Transition: Like</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b071bc715dc643c388edb362d39704c1/href">https://medium.com/media/b071bc715dc643c388edb362d39704c1/href</a></iframe><p>This transition gives us the swipe like animation. The transition needs start and end, which are rest and like, the duration is set to 100ms — we want the view to come back fast to its start state. onTouchUp is just for it. We explicitly set to the auto-complete transition to the start state when user takes off a finger. Let’s check the results so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*C383DMfJLvKJPk4JrlR2yg.gif" /></figure><h3>Issues during transition</h3><p>We are definitely still missing a few things :). Let’s free this transition beyond the boundaries of the grid element first. We need to set android:clipChildren=&quot;false&quot; on the RecyclerView element. Setting this property to false will allow the children views to draw outside of their bounds. Exactly what we needed. The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*5AX2fTEh2LmzzsFbMBwueA.gif" /></figure><p>Now, the children animate outside the parent, but another issue pops up. Even grid elements are stacked higher than the odd ones, which leads to the unpleasant effect of hiding the view behind its neighbor. We need to change Z transition or elevation of the active item.</p><p>At the beginning I was changing the elevation in the motion scene, but this gives me no effect. Then my colleague(<a href="https://medium.com/u/3723c77a132f">Damian Petla</a>) said: <em>You can raise the table in your apartment higher and higher, but you will never be on the same level as your neighbor living on the floor above you. S</em>peaking a language that the engineer understands: The recyclerView child needs to be modified, not the item in ViewHolder.</p><p>To manage the elevation properly, we need to know when the item starts animation and when it completes. In bind() function of ViewHolder, I set the MotionLayout.TransitionListener and invoked my custom state listener that pass the value to adapter and then to viewModel. Let’s see some code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0533c893ed91533dcb4f3a7b2e0173c8/href">https://medium.com/media/0533c893ed91533dcb4f3a7b2e0173c8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a7928b1d900fd06a41ee2d2c98c712c/href">https://medium.com/media/5a7928b1d900fd06a41ee2d2c98c712c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/436b2022154df83ec79ee7e6b1db7590/href">https://medium.com/media/436b2022154df83ec79ee7e6b1db7590/href</a></iframe><p>As you can see above, I expanded the functionality of animationStateListener to hold one more value, the item TAG. The tag helps to identify item flawlessly. The zTransition(elevation) magic happens in fragment. Check it out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb9417251a7f4a9382e9fa9d1e85004f/href">https://medium.com/media/bb9417251a7f4a9382e9fa9d1e85004f/href</a></iframe><p>Since the default elevation for RV item is 0, we just need to increase it to 1 at the start of animation and restart it to default when animation ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*QoyHkIkBURwfPHXFDlIMZw.gif" /></figure><h3>The Velocity Tracker error</h3><p>Sometimes the app crashes during the animation, with fatal error pointing to NPE on VelocityTracker. Quoting <a href="https://github.com/BBorombo">BBorombo</a>, who opens issue on the GitHub repo:</p><blockquote>The crash only occurs when you perform the animation and try to scroll the list, from outside the cell you played the animation from, but not every time.<br>Example :<br>Animation on Item2 + Scroll the list with a touch from the item 2 = OK<br>Animation on Item4 + Scroll the list with a touch from the item 6 = Crash</blockquote><p>After some investigation and internet search I’ve finally found the solution. All you need to do is to create a custom MotionLayout class, which use VelocityTracker in null safety way. As much and as little is needed to get rid of the fatal error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17bfbe9af6f5150b7589d27aea909b7e/href">https://medium.com/media/17bfbe9af6f5150b7589d27aea909b7e/href</a></iframe><h3>Item freeze</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*wwoVBvL4TlfDzsJBuWJdcw.gif" /><figcaption>Item freeze when scrolling RV</figcaption></figure><p>Another issue to tackle is the item freeze during scroll of recyclerView. The animation stops at current progress when list starts scroll. There are probably many solutions for this issue, I choose the easiest to implement. Instead of get freeze of item transition I will freeze recyclerView during animation. Hopefully we already have listener for animationState 😃.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/606d48c3e666d093c251e3a4776143d9/href">https://medium.com/media/606d48c3e666d093c251e3a4776143d9/href</a></iframe><p>I create custom RecyclerView that block all touch events when the variable swipeFrozen is set to true. The variable is changed in animationState observer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc22de29aabbea321538cc764b8666a4/href">https://medium.com/media/fc22de29aabbea321538cc764b8666a4/href</a></iframe><p>As you can see, I freeze recyclerView when animation starts and defroze itwhen animation completes. Additionally, to prevent a total freeze, I also defroze the recyclerView when user does pull to refresh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*_hnRcYB5or_6_FawSoCeBQ.gif" /><figcaption>freeze RecyclerView during item animation</figcaption></figure><h3>Transition: flyOff</h3><p>It is time to handle the fly off screen animation. We will send our item out of the screen to left or right, depending on our previous action. For that purpose, I prepared ConstraintSet called “goneRight”, which will gently animate item off-screen and trigger the item remove function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac9725fe8171e11f481aa3dcd5af074/href">https://medium.com/media/6ac9725fe8171e11f481aa3dcd5af074/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d197d5ab1e183f2c296513071d5d1621/href">https://medium.com/media/d197d5ab1e183f2c296513071d5d1621/href</a></iframe><p>The autoTransition function will perform the animation automatically when motionLayout will detect that start constraintSet is like. This will happen only after user releases his finger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Jqsq0kYV6XUjCiTrx4Bt8Q.gif" /><figcaption>Item fly off the screen after swipe</figcaption></figure><p>As you can see the item flies away, but the list is not refilled and it leaves an ugly hole. Let’s fix it 😃</p><h3>Add remove item listener</h3><p>The best place to inform the list that the item should be removed is the end of the swipe animation. I expanded onTransitionCompleted to inform the adapter when it should perform action. For simplicity, I call the same listener for like and dislike.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce39f8c1531c71e9ae176fbac5f45f53/href">https://medium.com/media/ce39f8c1531c71e9ae176fbac5f45f53/href</a></iframe><p>This listener, indeed removes the item from the list, but it is not removing the view from recyclerView. The view cell is still there, but it hides away of screen. We do not want to delete the view (it is not possible in recyclerVIew), instead we want to reset the constraintSet to default(rest state) and show the next item in that view. This is how recyclerView works. It recyclers views 😃</p><h3>Reset constraints to default</h3><p>To achieve that, we need to force motionLayout to set its default state and default transition, also we need to reset the progress from 1 to 0.</p><pre><em>private fun </em>resetTransition(motionLayout: MotionLayout?) {<br>    motionLayout?.<em>let </em><strong>{<br>        it</strong>.<em>progress </em>= 0f<br>        <strong>it</strong>.setTransition(R.id.<em>rest</em>, R.id.<em>like</em>)<br>    <strong>}<br></strong>}</pre><p>Invoke resetTransition function after removeItemListener and <em>voila!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*lxC3JDkjlZ8otq0-kl1THQ.gif" /></figure><h3>Make it shine ⭐️</h3><p>As you saw at the beginning of the article, the item changes during swipe. I added a green overlay with frame for like and red overlay with frame for dislike. Those overlays are standard View and are added to item layout. During swipe I manipulate the alpha of the overlay, using KeyFrameSet and KeyAttribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27af3675fb71a63ea001d2973b0b80cf/href">https://medium.com/media/27af3675fb71a63ea001d2973b0b80cf/href</a></iframe><p>Keyframes allow you to specify a change at a point in time during transition. The node: framePosition is exactly specifying it. The transition splits into 100 frames. Setting it to 50 means the alpha will change from 0 to 1 till 50% of transition. To make it work, set the initial value of alpha to 0 explicitly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*s2pMpJ-bDLFNKYcP3a5I0Q.gif" /></figure><h3>BONUS — wait for recycler to remove the item</h3><p>As you can see on above gif, there is a little glitch when item is removed from list. The problem occurs, because resetTransition is called immediately after we remove the item. The recyclerView does not have a time to properly react on that deletion. We should wait for the Adapter to perform deletion and then reset transition. To achieve this, I will use Kotlin coroutines in the same way <a href="https://medium.com/u/9303277cb6db">Chris Banes</a> shows in his article <a href="https://medium.com/androiddevelopers/suspending-over-views-19de9ebd7020">Suspending Over Views</a>.</p><p><strong>Await list changed</strong></p><p>First, let’s prepare a suspend function that will be waiting for item removal. We will pass this function to ViewHolder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85fe910524b242a9134d38edb2689b9/href">https://medium.com/media/d85fe910524b242a9134d38edb2689b9/href</a></iframe><p>The suspending function awaits for item removal. As Chris mentioned, the unregister of observer is needed to do not leak coroutine, then resume it with position that has been removed.</p><p><strong>Pass suspend function as function parameter</strong></p><p>This operation is fairly easy. In Kotlin we can pass suspend function as an argument and the only think we need to do is add keyword suspend in high-order function that will receive it. In our case it is a bind function of ViewHolder. Coroutine launch in TransitionListener.onTransitionCompleted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f7f7fa082ecd226cad4557da5f0b793/href">https://medium.com/media/3f7f7fa082ecd226cad4557da5f0b793/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*OT7qOPKhxxFRy-o753ooPg.gif" /></figure><h3>Afterword</h3><p>Motion Layout is right now (as of January 2020) in a beta stage, thus there are still things that do not work, are still glitchy and far from perfect. Still, it was fun to experiment with, worth the final effect of beautiful and smooth animations in my application.</p><p>Happy animating! 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a3838fe6b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/use-motion-layout-in-recyclerview-a5a3838fe6b6">Use Motion Layout in RecyclerView</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The beauty and the ugly of animating view on keyboard opens]]></title>
            <link>https://medium.com/schibsted-tech-polska/the-beauty-and-the-ugly-of-animating-view-on-keyboard-opens-8c1654da5fa3?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c1654da5fa3</guid>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[keyboard]]></category>
            <category><![CDATA[motion]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 13:55:26 GMT</pubDate>
            <atom:updated>2019-10-10T05:08:43.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*kY5JYfd8AvTTUMSHhOIMiw.jpeg" /></figure><p>Handling view changes when keyboard opens in Android is a painful game - everyone that tried that knows what I am talking about. Animating views on keyboard opens in fragment is even worst. I came up with a solution to this problem, but it is still far from perfect. In this article I will try to show you what ugly tricks needed to be done to create a slick animation when softInputKeyboard opens.</p><h3>Defining problem</h3><p>In GoodOnes (Swedish/Norwegian dating app by Mötesplatsen), we always aim for having a cool design, which also includes animations. One of the requirements from our designer was particularly complicated. See that below GIF from the iOS implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*FCqNneZEh1ioCCSn1OzjWA.gif" /><figcaption>Above gif shows GoodOnes like message functionality. This is recorded on dev environment.</figcaption></figure><p>We have several actions that are animating here in one sequence:</p><ul><li>photo squeeze by about 5% to the center;</li><li>new text and icon appears on the top;</li><li>green gradient applies;</li><li>white frame around green view appears;</li><li>keyboard is opening;</li><li>EditText together with 2 buttons are moving up;</li><li>The background photo(next person) is visible under the green view;</li><li>Both pictures do not move when keyboard open;</li></ul><p>We were trying to accomplish that using shared element transitions, some complex animation xmls and a lot of callbacks for keyboard opening. The effect was not satisfying. But then we met MotionLayout and everything changed.</p><h3>Building a motion scene</h3><p>MotionLayout is a class available in the ConstraintLayout 2.0 library that lets create great animations right from the XML. If you want to start experimenting with it, here is a good place to look at: <a href="https://medium.com/google-developers/introduction-to-motionlayout-part-i-29208674b10d">Introduction to MotionLayout</a></p><p>Lets check at layout hierarchy :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b8415c2fba29206d63ef8587459081/href">https://medium.com/media/72b8415c2fba29206d63ef8587459081/href</a></iframe><p>Two things that should draw our attention :</p><ul><li>The root layout is type of <em>androidx.constraintlayout.motion.widget.MotionLayout</em></li><li>There is a layoutDescription attribute used that point on the xml scene file: <em>app:layoutDescription=”@xml/send_like_msg_scene”</em></li></ul><p>The scene file is the place where all the magic starts. Let’s dive into the first part of animation displayed to user: <strong>squeeze photo by 5%</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2933128d2084b96b7a690be9ad15c0/href">https://medium.com/media/2b2933128d2084b96b7a690be9ad15c0/href</a></iframe><p>If you had contact with Motion Layout before, the code above is pretty self-explanatory. For those who have doubts, a few words about the above functions.</p><ul><li>ConstraintSet — the most important xml tag in MotionScene. Set contains all constraints that are taking part in animation</li><li>Constraint — the basic tag that override attributes from layout file( if not used along with &lt;Layout&gt;, &lt;Transform&gt; etc.), more info in <a href="https://developer.android.com/reference/android/support/constraint/motion/MotionLayout#constraint">docs</a></li><li>Transition — here, we are informing animator what are the start and end position for layout, we can also set the duration, motion interpolator, autoTransition etc</li></ul><p>With those set up, the current animation looks as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*RcFbFuzVleKpaskjcmIX0A.gif" /></figure><p>Now, let’s apply this <strong>green gradient. </strong>I have prepared it together with a white frame, so we will combine two actions into a one element. The construction of this xml is not part of this article, but if you would like to check it, <a href="https://gist.github.com/PiotrPrus/fd962ba24dcc5aa5dd98ce7b34f15351"><em>here</em></a> is the source.</p><p>Since our main imageView is animating nice and the frame is a child view, we do not need to add anything to our motionScene. We just need to constrain the frame. Here is the effect 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*4kxxIYSRF008rVtjl68W-Q.gif" /></figure><p>Similarly for the buttons, text and other view components. Those are all child view for our main animating image (see view hierarchy posted before). Works like this:👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*g49whWeJMYrEkuWEJIE_BA.gif" /></figure><p>So far, so good. The animation looks really nice and smooth, but what with the keyboard? Unfortunately everything jumps and ruins the whole smoothness of this view. Let’s try to fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*_d_sc93xggheS8_eY27bTA.gif" /></figure><h3>Keyboard opens = troubles</h3><p>At the beginning I tried all available windowSoftInputMode that you can set in AndroidManifest file. Each is explained <a href="https://developer.android.com/guide/topics/manifest/activity-element.html#wsoft">here</a>. Unfortunately, none of them satisfied our needs. After that I tried to make a listener that notify the app when the keyboard opens and move the views as designed, but I ended up with really ugly and jumpy view. The clever hack was needed, and eventually I’ve found the one.</p><h3>The hack</h3><p>I needed some way to move only a few views and keep the rest of UI in the exact same place. Screenshot as a background of layout suited perfectly. This technique is used in a UI test. In Android testing support library there is a class Screenshot that does exactly what I needed, but tho it is not available in normal package. I needed to catch Bitmap. Below code shows how to do it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c96d4eaecc72ebda8a385749c135c58/href">https://medium.com/media/1c96d4eaecc72ebda8a385749c135c58/href</a></iframe><p>Since I needed background image and foreground image (the one with frame and green gradient) static, the screenshot covers the whole screen (window.decorView.rootView)</p><p>We have a screenshot that is displayed as window background drawable. Now, we need to take it (screenshot) in right moment after our view opens and clear it when it is no longer needed. Transition Listener from motion layout is keen to help us out.</p><h3>Observe transition changes</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/428199174096921d3013d8b67393357c/href">https://medium.com/media/428199174096921d3013d8b67393357c/href</a></iframe><p>As seen in the code snippet above, the Transition Listener has five override functions that we can use to manipulate our views depending on animation progress. I will use two of them, onTransitionStarted and onTransitionCompleted.</p><p>Inside onTransitionCompleted I check following:</p><pre><em>if </em>(endId == R.id.<em>endScene </em>&amp;&amp; !isScreenshotTaken) {<br>    isScreenshotTaken = <em>true<br>    </em>takeScreenshot()<br>}</pre><p>My endScene is the one with a view settled on position, squeezed by 5%, green gradient applied, etc. When everything is set, I can make my screenshot and apply it as backgroundDrawable. After that I request focus on editText and keyboard show off, moving only those views that are still visible. The rest is just a screenshot.</p><p>Opening up the keyboard triggers again onTransitionCompleted. I use this opportunity to set up visibility for views. Let’s have a look how this scenario looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*kOeQUvhi5B6lGlG5OlWnBg.gif" /></figure><p>At the end it is still a little jumpy, that’s because of a bug that we have in loading photos on the main fragment, nothing motionLayout related. 😃</p><p>During closing we need to clear bitmap (screenshot) and apply default backgroundDrawable. Those steps looks as follows:</p><pre>requireActivity().<em>window</em>.setBackgroundDrawable(defaultBackgroundDrawable)<br>binding.etSendLikeMsgMessage.<em>hideKeyboard</em>()<br>binding.motionLayoutRoot.transitionToStart()<br>releaseBitmapFromMemory()</pre><p>set background drawable to default value, you can get this value in initial state of fragment by <em>requireActivity().window.decorView.background</em></p><ul><li>hide keyboard</li><li>Trigger the transition to start, which will create smooth animation from endScene to startScene defined previously in motion scene</li><li>Release a bitmap. This step is important, cause recycling the bitmap simply allows it to be garbage collected.</li></ul><h3>The last animation</h3><p>Something is missing here, right? It is dating app, so swiping is an important feature. Let’s swipe this view out, right after user send the message. We will use Motion Layout for that, of course.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beb7af46863ea9c5d5b71b6ebd7ef1ab/href">https://medium.com/media/beb7af46863ea9c5d5b71b6ebd7ef1ab/href</a></iframe><p>Each motionLayout transition has two constraint sets, start and end. We will use our endScene as start and add endSwipeScene that will leads to close the view. The transition will start on click event on send button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ccafcaea2d53245d8c94d0d253fc40/href">https://medium.com/media/67ccafcaea2d53245d8c94d0d253fc40/href</a></iframe><p>To produce nice swipe animation we need translation and rotation. After some testing I decide to go for a 45 degree angle and 600dp translationX.</p><p>The final effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*IKDWqPXc-NGb8Mf3uV7vqw.gif" /></figure><p>Also in this scenario, this is important to release memory, set background to default and hide the keyboard. 😃</p><p>If you have any tip for this specific animation case or have questions about presented layout, feel free to comment.</p><p>Until next time.</p><p>Piotr</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c1654da5fa3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/the-beauty-and-the-ugly-of-animating-view-on-keyboard-opens-8c1654da5fa3">The beauty and the ugly of animating view on keyboard opens</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flexible logging strategy for iOS app]]></title>
            <link>https://medium.com/schibsted-tech-polska/flexible-logging-strategy-for-ios-app-a524ac0dc0f5?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/a524ac0dc0f5</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bogusław Parol]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 11:03:58 GMT</pubDate>
            <atom:updated>2019-09-17T08:58:01.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdgkU9sQWvaZnuiGLyc5_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Neel</a> on <a href="https://unsplash.com/search/photos/research?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>One of the most important thing that helps to reach high level of app quality is getting as much information from our apps users as it’s possible.</strong></p><p>There is a bunch of great logging libraries out there, every one of them has some pros and cons. There is also os.log provided by <a href="https://developer.apple.com/documentation/os/logging">Apple</a>, that lets us to read logs in very good manner using <em>Console</em> application or stream it directly to <em>Terminal</em>. You can find tons of great articles describing how to use all of them, so I will not focus on that in this post.</p><p><strong>Instead, I would like to share my way of providing flexible logging to different target systems using different levels </strong>. So, let’s get it started.</p><p>TLDR; use dependency injection and build a facade-like function to dispatch log message to different targets. 😎</p><p>First of all we need to think about which target systems we will support. Even though we want to build flexible, target-independent logging experience, it’s good to think for a moment what kind of information every possible target will need. In my projects usually I support:</p><ul><li>logging to <em>XCode</em> console that helps me resolving issues while debugging</li><li>logging to <em>os.log</em> library that lets me and any other interested team member (i.e. tester) to read logs directly from <em>Console</em> app</li><li>logging to <em>Crashlytics</em> or similar QA cloud platform</li></ul><p>Actually, first two are interconnected — logging using os.log will cause your log messages to appear in <em>XCode</em> console as well.</p><p>os.log uses concept of <em>subsystems</em> and <em>categories</em>, both help us to organize our logs and read and filter them efficiently. We can borrow concept of categories from Apple and use it in our solution. Let’s assume for now that we will use three categories:</p><ul><li><em>general </em>— a default category used if we don’t want to use any specific category,</li><li><em>viewCycle </em>— for logging events like loading new screen or removing one</li><li><em>memoryManagement</em> — used for logging creation and destruction of important objects (this category is very helpful if we want to detect memory related issues).</li></ul><p>Add as many categories as you need, i.e. <em>networking </em>seems to me as a good candidate. Given that, we can create enum that will store our categories:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77678da815932061dfd3809056d2fc2/href">https://medium.com/media/a77678da815932061dfd3809056d2fc2/href</a></iframe><p>Next, we need to define log levels according to our needs. The most common levels used by different platforms are: <em>debug</em>, <em>info</em>, <em>warning</em>, and <em>error</em>. We can extend this set with <em>fault</em> level, which is used by Apple for system-level or multi-process errors only:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4ad272f8bb6b99d72248fc541d4334/href">https://medium.com/media/1d4ad272f8bb6b99d72248fc541d4334/href</a></iframe><p>We used Int based enum that can be compared in order to manage log level efficiently. Next, we can define protocol LogHandler, that different target systems will implement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31732a29514ce4b6101034ec2277a828/href">https://medium.com/media/31732a29514ce4b6101034ec2277a828/href</a></iframe><p>Now, we need a mechanism for dispatching log messages to particular targets. We use dependency injection for defining handlers list, so we can write tests for the logger further.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4051ec1177490e192a4332cf375af1d3/href">https://medium.com/media/4051ec1177490e192a4332cf375af1d3/href</a></iframe><p>Thanks to filter{$0.supportedLevel ≥ level} line and the way how we defined our LogLevel enum, logs will be delivered to appropriate handlers. For instance, if we want to log message with <em>info</em> level that has <em>rawValue</em> equal 3, only handlers with supported log level that have rawValue ≥ 3 will print that message (<em>info</em>, <em>debug</em>, <em>verbose</em>).</p><p>Let’s now try to implement handler for logging to os.log library. The logging is implemented by OSLog class there. To use the most of its capabilities, we can use our categories. Firstly we need to create OSLog instance for every category that we have. Convenient way for doing this is extending the class. Also, we would need to map our custom LogLevel to Apple’s OSLogType:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61180bbccd36c02cb37e4cf9da6d39a8/href">https://medium.com/media/61180bbccd36c02cb37e4cf9da6d39a8/href</a></iframe><p>Having this, creating log handler for os.log is trivial:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/549eadb66dea4add8589c71534ecaf99/href">https://medium.com/media/549eadb66dea4add8589c71534ecaf99/href</a></iframe><p>Of course we don’t need to add all available arguments to the format string like I did above, however, because the same message will be printed directly to the <em>XCode</em> console, that seem to be less inappropriate.</p><p>In order to provide easy usage of our logger and being able to pass implicitly details like filename, function name, line and column further, we can wrap it into a function that defines bunch of default arguments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5ab4c14b94033d42a3a1299a8207cdc/href">https://medium.com/media/e5ab4c14b94033d42a3a1299a8207cdc/href</a></iframe><p>Now adding new log handlers for any other targets is super easy. We just need to inject appropriate handlers to our Logger somewhere at the start of the app 🎉</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afbdb44a3cb865b1d9052c651e1c8f8e/href">https://medium.com/media/afbdb44a3cb865b1d9052c651e1c8f8e/href</a></iframe><p>If this solution looks interesting to you, you can check the demo project available at <a href="https://github.com/bparol/FlexibleLoggingExample">Github</a>.</p><p>Please let me if you have any comments or suggestions, just send me an email at boguslaw.parol@gmail.com</p><p>Thanks for reading! 🙇 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a524ac0dc0f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/flexible-logging-strategy-for-ios-app-a524ac0dc0f5">Flexible logging strategy for iOS app</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS ECS — quickly create environment for your dockerized apps (HA!)]]></title>
            <link>https://medium.com/schibsted-tech-polska/aws-ecs-quickly-create-environment-for-your-dockerized-apps-ha-4a3b0c6fbbf3?source=rss----dc5f2a4b4e48---4</link>
            <guid isPermaLink="false">https://medium.com/p/4a3b0c6fbbf3</guid>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Damian Tykałowski]]></dc:creator>
            <pubDate>Wed, 25 Jul 2018 08:08:25 GMT</pubDate>
            <atom:updated>2018-05-18T11:36:01.047Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>AWS ECS — quickly create environment for your dockerized apps (HA!) — CLI versionTL;DR (adjust variables for yourself!).</h3><p>Go to GitHub and clone repository, change variables, run it.</p><p><a href="https://github.com/d47zm3/devops/tree/master/aws/ecs-cluster">https://github.com/d47zm3/devops/tree/master/aws/ecs-cluster</a></p><p>You will need AWS CLI, JQ and ECS-CLI (links in script).</p><p><strong>First part (VPC creation) comes from here, I modified it a bit to add another subnet for HA and more open ports: </strong><a href="https://medium.com/@brad.simonin/create-an-aws-vpc-and-subnet-using-the-aws-cli-and-bash-a92af4d2e54b">https://medium.com/@brad.simonin/create-an-aws-vpc-and-subnet-using-the-aws-cli-and-bash-a92af4d2e54b</a></p><p>Since the whole setup consists of few files, I won’t paste them here, they all are available in my GitHub repository. Here I will discuss more important parts of it and how it all runs together. Let’s start with VPC. I’ve took this part from Brad with his permission, I just added another subnet for HA and a rule for loadbalancer as well as some other small tweaks.</p><p>It’s time to explain everything, step-by-step. First we need to have VPC that would keep our EC2 instances for ECS cluster, underneath there are a lot of resources to be created, thus everything connects properly. VPC will have two subnets for HA located in a two separated zones. In any case, tags will be added, thus it’s easy to identify ECS resources, all required routes, Internet gateway, firewall rules, all that jazz. We will use two custom tools besides obviously required AWS CLI, JQ to parse responses from AWS CLI client (to save IDs) and ECS-CLI client to manage ECS cluster. Couple of variables to be set here… In addition to the first few ones, like name, region or SSH keypair (<strong>which you will have to create yourself if you want to use one</strong>) there is no need to change network settings. In any case, I added comments for variables that might be confusing, hopefully it’s self-explaining.</p><pre>cluster_name=&quot;ecs-medium&quot;<br># where cluster will store logs, can take name off cluster or application<br>log_group_name=&quot;${cluster_name}-log-group&quot;<br>region=&quot;eu-west-2&quot;<br># keypair if you want to SSH into instances<br>keypair=&quot;d47zm3&quot;<br>service_name=&quot;${cluster_name}-service&quot;</pre><pre># on what port on container your application listens<br>target_port=80</pre><pre># on what port will loadbalancer listen<br>listener_port=80</pre><pre># how container (task) should be named in ecs, web, api, proxy?<br>container_name=&quot;web&quot;</pre><pre>name=&quot;ECSMedium&quot;<br>vpc_name=&quot;${name} VPC&quot;</pre><pre>profile_name=&quot;ecs-medium&quot;<br>loadbalancer_name=&quot;${cluster_name}-loadbalancer&quot;<br>loadbalancer_targets_name=&quot;${cluster_name}-targets&quot;</pre><pre>role_name=&quot;ECSMediumRole&quot;<br>tier_class=&quot;t2.small&quot;</pre><pre>availability_zone_1=&quot;eu-west-2a&quot;<br>availability_zone_2=&quot;eu-west-2b&quot;</pre><pre>subnet_name_1=&quot;${name} Subnet 1&quot;<br>subnet_name_2=&quot;${name} Subnet 2&quot;</pre><pre>gateway_name=&quot;${name} Gateway&quot;<br>route_table_name=&quot;${name} Route Table&quot;<br>security_group_name=&quot;${name} Security Group&quot;<br>vpc_cidr_block=&quot;10.0.0.0/16&quot;<br>subnet_cidr_block_1=&quot;10.0.1.0/24&quot;<br>subnet_cidr_block_2=&quot;10.0.2.0/24&quot;</pre><pre># allow traffic on these ports from anywhere<br>port_cidr_block_22=&quot;0.0.0.0/0&quot;<br>port_cidr_block_80=&quot;0.0.0.0/0&quot;<br>port_cidr_block_443=&quot;0.0.0.0/0&quot;</pre><pre># allow traffic out anywhere<br>destination_cidr_block=&quot;0.0.0.0/0&quot;</pre><p>After the first part you will see message like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7f5M6vEh9e2FJARfmJbxA.png" /></figure><p>You can check out your AWS console to see newly created VPC, ready with all dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mr_p8uDRflYOFq-fygzTGA.png" /></figure><p>After VPC is created, it’s time for some IAM magic. We will need the IAM role with some permissions, so your ECS instances can pull images from your private ECR registry (it’s a private Docker registry hosted on AWS). To achieve this task, we need to use some external files with definitions of permissions, not too much to talk about.</p><p>Now it’s time to get started with ECS part itself. While you could start-up ECS cluster without all these options, and it would create VPC, EC2 etc. instances for you, you could quickly hit the VPC limit when managing multiple clusters, also making mess that way is also an easy task. It’s better to have one (or more, your choice) dedicated VPC to manage for ECS cluster instances and have control over them (and customize them on the way). Again, added comments are explaining steps one by one.</p><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Configure ECS profile...&quot;<br>ecs-cli configure profile --profile-name ${profile_name} --access-key ${AWS_ACCESS_KEY_ID} --secret-key ${AWS_SECRET_ACCESS_KEY}</pre><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Configure ECS cluster before launch...&quot;<br>ecs-cli configure --cluster ${cluster_name} --region ${region} --config-name ${profile_name} --default-launch-type EC2</pre><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Bring up EC2 instance...&quot;<br># bring up cluster<br>ecs-cli up  --size 2 --instance-type ${tier_class} --vpc ${vpc_id} --cluster-config ${profile_name} --subnets ${subnet_id_1},${subnet_id_2} --security-group ${group_id} --instance-role ${role_name} --keypair ${keypair} --ecs-profile ${profile_name}</pre><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Wait until EC2 instances are registered...&quot;<br>sleep 60</pre><p>After executing the next part, you will see your cluster created, since machines are in different AZs it’s highly available</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZdUELmpB32m9Lh-ew0IEA.png" /></figure><p>Now, we’ve got EC2 machines with configured Docker that we can control from ECS dashboard. Now we can set up services and tasks on them, but what is a service and what is a task? As for the task, we need to start with a task definition, that is described in docker-compose.yml. It specifies image to use, mounts, port forwards, logging configuration and such. Task i simply running instance of task definition. You start container with all settings specified. Service on the other hand makes sure proper amount of tasks is running, if one stops, it restarts it and such, it ties load balancer so it points to your running tasks, ensures placement strategy so containers are spreaded etc. Find more info here: <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_definition_parameters.html">https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_definition_parameters.html</a></p><p>But before we define our tasks and services, let’s create load balancer for it. Notice that, once you create service tied to one load balancer, you cannot change load balancer. You will need to re-create service. Amazon has two types of load balancer available, Classic Load Balancer and Elastic/Application Load Balancer. For us, what is important is fact, using Classic Load Balancer, we won’t be able to set up dynamic port forwarding and we cannot do no-downtime deployments. So we will use Application Load Balancing that supports this feature.</p><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Create Application Load Balancer in chosen subnets...&quot;<br>alb_response=$( aws elbv2 --region  ${region} create-load-balancer --name ${loadbalancer_name} --subnets ${subnet_id_1} ${subnet_id_2} --security-groups ${group_id} )<br>alb_arn=$( echo -e &quot;${alb_response}&quot; |  jq &#39;.LoadBalancers[] | .LoadBalancerArn&#39; | tr -d &#39;&quot;&#39; )<br>alb_dnsname=$( echo -e &quot;${alb_response}&quot; |  jq &#39;.LoadBalancers[] | .DNSName&#39; | tr -d &#39;&quot;&#39;)</pre><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Create Target Group for ECS instances (targeting port ${target_port})...&quot;<br>target_group_response=$( aws elbv2 --region ${region} create-target-group --name ${loadbalancer_targets_name} --protocol HTTP --port ${target_port} --vpc-id ${vpc_id} )<br>target_group_arn=$( echo -e &quot;${target_group_response}&quot; |  jq &#39;.TargetGroups[] | .TargetGroupArn&#39; | tr -d &#39;&quot;&#39; )</pre><pre>echo &quot;[*] [$( date +&#39;%H:%M:%S&#39;)] Create Listener that will forward traffic to registered instances...&quot;<br>listener_response=$( aws elbv2 --region ${region} create-listener --load-balancer-arn ${alb_arn}  --protocol HTTP --port ${listener_port}  --default-actions Type=forward,TargetGroupArn=${target_group_arn} )</pre><p>Crucial for dynamic port forwarding is this “strange” 0 port number mapping in docker-compose.yml</p><pre>version: &#39;2&#39;<br>services:<br>  web:<br>    image: httpd:2.4.32<br>    ports:<br>     - &quot;0:80&quot;<br>    logging:<br>      driver: awslogs<br>      options:<br>        awslogs-group: ecs-medium<br>        awslogs-region: eu-west-2<br>        awslogs-stream-prefix: example</pre><p>This means, it will map any random port on host to 80 port in container. ECS (or rather service) will take care of registering this random port correctly in target group. Other than that we specify group for logs, it will be created and stream-prefix, it allows us to recognize quickly from which container stream logs come from. Now we are ready to define our task and start service. Below I present output from script and the final result. From timestamps you can see we managed to close in 5 minutes with whole environment ready!</p><pre>[*] [13:45:42] Creating VPC...</pre><pre>[*] [13:46:01] VPC created, VPC ID: vpc-5f6eb437<br>[*] [13:46:01] Use Subnet ID subnet-fb4ab481 and subnet-8a5659c7, for Security Group ID sg-ebb61580<br>[*] [13:46:01] AWS resources will be created in eu-west-2, and in these AZs: eu-west-2a, eu-west-2b<br>[*] [13:46:01] Dumping values for future usage to ecs.values file...<br>[*] [13:46:01] Creating IAM role for ECS instances... (gives you possibility to use your ECR - AWS private registry for example<br>[*] [13:46:05] Configure ECS profile...<br>INFO[0000] Saved ECS CLI profile configuration ecs-medium.<br>[*] [13:46:05] Configure ECS cluster before launch...<br>INFO[0000] Saved ECS CLI cluster configuration ecs-medium.<br>[*] [13:46:05] Bring up EC2 instance...<br>INFO[0000] Created cluster                               cluster=ecs-medium region=eu-west-2<br>INFO[0001] Waiting for your cluster resources to be created...<br>INFO[0001] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS<br>INFO[0061] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS<br>INFO[0122] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS<br>Cluster creation succeeded.<br>[*] [13:48:38] Wait until EC2 instances are registered...<br>[*] [13:49:38] Create Application Load Balancer in chosen subnets...<br>[*] [13:49:40] Create Target Group for ECS instances (targeting port 80)...<br>[*] [13:49:41] Create Listener that will forward traffic to registered instances...<br>[*] [13:49:41] Create Service in ECS cluster using created Target Group...<br>DEBU[0000] Parsing the compose yaml...<br>DEBU[0000] Opening compose files: docker-compose.yml<br>DEBU[0000] [0/1] [web]: Adding<br>DEBU[0000] [0/1] [default]: EventType: 32<br>DEBU[0000] Parsing the ecs-params yaml...<br>DEBU[0000] Transforming yaml to task definition...<br>DEBU[0000] Finding task definition in cache or creating if needed  TaskDefinition=&quot;{\n  ContainerDefinitions: [{\n      Command: [],\n      Cpu: 0,\n      DnsSearchDomains: [],\n      DnsServers: [],\n      DockerLabels: {\n\n      },\n      DockerSecurityOptions: [],\n      EntryPoint: [],\n      Environment: [],\n      Essential: true,\n      ExtraHosts: [],\n      Image: \&quot;httpd:2.4.32\&quot;,\n      Links: [],\n      LinuxParameters: {\n        Capabilities: {\n\n        }\n      },\n      LogConfiguration: {\n        LogDriver: \&quot;awslogs\&quot;,\n        Options: {\n          awslogs-stream-prefix: \&quot;example\&quot;,\n          awslogs-group: \&quot;ecs-medium\&quot;,\n          awslogs-region: \&quot;eu-west-2\&quot;\n        }\n      },\n      Memory: 512,\n      MountPoints: [],\n      Name: \&quot;web\&quot;,\n      PortMappings: [{\n          ContainerPort: 80,\n          HostPort: 0,\n          Protocol: \&quot;tcp\&quot;\n        }],\n      Privileged: false,\n      ReadonlyRootFilesystem: false,\n      Ulimits: [],\n      VolumesFrom: []\n    }],\n  Cpu: \&quot;\&quot;,\n  ExecutionRoleArn: \&quot;\&quot;,\n  Family: \&quot;ecs-medium-service\&quot;,\n  Memory: \&quot;\&quot;,\n  NetworkMode: \&quot;\&quot;,\n  RequiresCompatibilities: [\&quot;EC2\&quot;],\n  TaskRoleArn: \&quot;\&quot;,\n  Volumes: []\n}&quot;<br>INFO[0000] Using ECS task definition                     TaskDefinition=&quot;ecs-medium-service:3&quot;<br>WARN[0000] Failed to create log group ecs-medium in eu-west-2: The specified log group already exists<br>INFO[0000] Created an ECS service                        service=ecs-medium-service taskDefinition=&quot;ecs-medium-service:3&quot;<br>WARN[0001] Failed to create log group ecs-medium in eu-west-2: The specified log group already exists<br>DEBU[0001] Updated ECS service                           count=1 service=ecs-medium-service<br>INFO[0001] Updated ECS service successfully              desiredCount=1 serviceName=ecs-medium-service<br>INFO[0016] (service ecs-medium-service) has started 1 tasks: (task 89307d75-3001-496a-9117-85290f46d053).  timestamp=&quot;2018-05-10 11:49:50 +0000 UTC&quot;<br>INFO[0031] Service status                                desiredCount=1 runningCount=1 serviceName=ecs-medium-service<br>INFO[0031] (service ecs-medium-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:eu-west-2:506673647732:targetgroup/ecs-medium-targets/4e4a92c73085203c)  timestamp=&quot;2018-05-10 11:50:03 +0000 UTC&quot;<br>INFO[0031] ECS Service has reached a stable state        desiredCount=1 runningCount=1 serviceName=ecs-medium-service<br>[*] [13:50:13] Scale Service to 2 replicas...<br>DEBU[0000] Parsing the compose yaml...<br>DEBU[0000] Opening compose files: docker-compose.yml<br>DEBU[0000] [0/1] [web]: Adding<br>DEBU[0000] [0/1] [default]: EventType: 32<br>DEBU[0000] Parsing the ecs-params yaml...<br>DEBU[0000] Transforming yaml to task definition...<br>DEBU[0000] Updated ECS service                           count=2 service=ecs-medium-service<br>INFO[0000] Updated ECS service successfully              desiredCount=2 serviceName=ecs-medium-service<br>INFO[0000] Service status                                desiredCount=2 runningCount=1 serviceName=ecs-medium-service<br>INFO[0015] (service ecs-medium-service) has started 1 tasks: (task 087bb880-3fd1-4228-b994-d589d171a75c).  timestamp=&quot;2018-05-10 11:50:22 +0000 UTC&quot;<br>INFO[0030] Service status                                desiredCount=2 runningCount=2 serviceName=ecs-medium-service<br>INFO[0030] ECS Service has reached a stable state        desiredCount=2 runningCount=2 serviceName=ecs-medium-service<br>[*] [13:50:43] Finished! Reach your service at ecs-medium-loadbalancer-1120207948.eu-west-2.elb.amazonaws.com !</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kX2MwEuOlXbcQbbIUApSyQ.png" /></figure><p>We can see our service running with two tasks (as inside script it’s scaled to two instances). By default placement strategy for tasks, is spread meaning tasks will be spread across available ECS instances. As you see basic metrics, CPU and memory utilization are available at hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh97bytYLzOxCe6e_fAjIA.png" /></figure><p>To check logs from this cluster and it’s containers, choose any of tasks, expand container view (in my case web) and click on “<strong>View logs in CloudWatch</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDim-az4DY48pIPMPK5XbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgTh1ZSSi6tZlrWRiZOLhQ.png" /></figure><p>Note that each container has it’s own log stream</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vY7xyswxKfV8U9nDAqzjmg.png" /></figure><p>What to do if you want to roll new image without downtime? It’s easy, specify new version in docker-compose.yml file and run deploy script below, remember to specify same values. Also add timeout flag since, even smallest deployments takes little longer than 5 minutes and it timeouts…</p><pre>#!/bin/bash</pre><pre>cluster_name=&quot;ecs-medium&quot;<br>service_name=&quot;${cluster_name}-service&quot;<br>profile_name=&quot;ecs-medium&quot;</pre><pre>ecs-cli compose --verbose --file docker-compose.yml --cluster-config ${profile_name} --project-name ${service_name} service up --timeout 10</pre><p>And here’s output from deployment.</p><pre>12:26:52 SEALS/ECS-Project-Base [~d47zm3@w0rk~] » (⎈ |gke:default) ./deploy.sh<br>DEBU[0000] Parsing the compose yaml...<br>DEBU[0000] Opening compose files: docker-compose.yml<br>DEBU[0000] [0/1] [web]: Adding<br>DEBU[0000] [0/1] [default]: EventType: 32<br>DEBU[0000] Parsing the ecs-params yaml...<br>DEBU[0000] Transforming yaml to task definition...<br>...<br>INFO[0000] Using ECS task definition                     TaskDefinition=&quot;ecs-medium-service:1&quot;<br>DEBU[0000] Updated ECS service                           count=2 service=ecs-medium-service taskDefinition=&quot;ecs-medium-service:1&quot;<br>INFO[0000] Updated the ECS service with a new task definition. Old containers will be stopped automatically, and replaced with new ones  desiredCount=2 serviceName=ecs-medium-service taskDefinition=&quot;ecs-medium-service:1&quot;<br>INFO[0000] Service status                                desiredCount=2 runningCount=2 serviceName=ecs-medium-service<br>INFO[0030] Service status                                desiredCount=2 runningCount=4 serviceName=ecs-medium-service<br>INFO[0030] (service ecs-medium-service) has started 2 tasks: (task 0eded47d-82c1-4862-ac22-66912a3150ff) (task 039c6cb2-dcf4-43ff-95fa-331ca1d4038a).  timestamp=&quot;2018-05-10 10:27:13 +0000 UTC&quot;<br>INFO[0045] (service ecs-medium-service) registered 2 targets in (target-group arn:aws:elasticloadbalancing:eu-west-2:506673647732:targetgroup/ecs-medium-targets/febcb7fe7daf5c72)  timestamp=&quot;2018-05-10 10:27:24 +0000 UTC&quot;<br>INFO[0060] (service ecs-medium-service) deregistered 2 targets in (target-group arn:aws:elasticloadbalancing:eu-west-2:506673647732:targetgroup/ecs-medium-targets/febcb7fe7daf5c72)  timestamp=&quot;2018-05-10 10:27:46 +0000 UTC&quot;<br>INFO[0060] (service ecs-medium-service) has begun draining connections on 2 tasks.  timestamp=&quot;2018-05-10 10:27:46 +0000 UTC&quot;<br>INFO[0362] Service status                                desiredCount=2 runningCount=2 serviceName=ecs-medium-service<br>INFO[0362] (service ecs-medium-service) has stopped 2 running tasks: (task 8202859b-ef90-4d60-bae5-1d1cf9b935e8) (task 8fd1903b-51ce-4750-98c7-4112d6fca84a).  timestamp=&quot;2018-05-10 10:32:52 +0000 UTC&quot;<br>INFO[0377] ECS Service has reached a stable state        desiredCount=2 runningCount=2 serviceName=ecs-medium-service</pre><p>That’s it, you have a ready infrastructure for your containerized application that has logging and monitoring, which are must for success. Also, if you just play with it do not forget to clean up resources, or it will eat your money quickly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3b0c6fbbf3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schibsted-tech-polska/aws-ecs-quickly-create-environment-for-your-dockerized-apps-ha-4a3b0c6fbbf3">AWS ECS — quickly create environment for your dockerized apps (HA!)</a> was originally published in <a href="https://medium.com/schibsted-tech-polska">Schibsted Tech Polska</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>