<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Josep Rodriguez on Medium]]></title>
        <description><![CDATA[Stories by Josep Rodriguez on Medium]]></description>
        <link>https://medium.com/@josep.rodriguez?source=rss-b5fea64e704b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HHnyvHFHNyv7_O8H2yFjgg.jpeg</url>
            <title>Stories by Josep Rodriguez on Medium</title>
            <link>https://medium.com/@josep.rodriguez?source=rss-b5fea64e704b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:48:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josep.rodriguez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling engineering teams]]></title>
            <link>https://medium.com/@josep.rodriguez/scaling-engineering-teams-654fd1a98fe?source=rss-b5fea64e704b------2</link>
            <guid isPermaLink="false">https://medium.com/p/654fd1a98fe</guid>
            <category><![CDATA[team-collaboration]]></category>
            <category><![CDATA[team-management]]></category>
            <category><![CDATA[team-building]]></category>
            <dc:creator><![CDATA[Josep Rodriguez]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 15:55:28 GMT</pubDate>
            <atom:updated>2021-11-09T16:03:50.293Z</atom:updated>
            <content:encoded><![CDATA[<p>The purpose of this guide is to provide guidance on how to manage the complexities of scaling up a team.</p><p>As most things that involve people, nothing is black and white, so you’ll have to balance what’s described here to your specific team and consider which of these actions make sense, and which don’t.</p><p>We also avoid being overly specific so as to ensure we are not caught up in the detail.</p><p>First of all, we need to gauge in which size group the team is.</p><figure><img alt="A team at work" src="https://cdn-images-1.medium.com/max/1024/0*Gz_UU4YvLpnLzgf5" /><figcaption>Photo by <a href="https://unsplash.com/@youxventures?utm_source=medium&amp;utm_medium=referral">You X Ventures</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Definition of “Team”</h3><p>To avoid confusion about who do we include in a team, we’ll define team as the group of individuals who actively take part in delivering project backlog items present in the board of the team.</p><h3>Identifying what kind of team size you are in</h3><p>We will differentiate 3 types of teams:</p><ul><li><strong>Small teams</strong>. Where we would ideally want to operate in. A small team will be efficient and nimble.</li><li><strong>Medium teams</strong>. There’s an awkward phase of growth where you start noticing some issues, but it feels like splitting the teams would result in teams that are too small, or that don’t have the cross functional skills that they’d need to deliver software effectively.</li><li><strong>Large teams</strong>. A large team is when the size of the team has become unbearable and splitting the team is a necessity. Ultimately, we’ll have to split the team into smaller ones that are independent enough not to revert into thinking they are the same large team, which would regress the issues we try to avoid.</li></ul><h3>Warnings of your team size</h3><p>There’s no hard limit on maximum team size, as it will be very context specific (a general rule of thumb is less than 9 people).</p><p>This section aims to call out some signs that <em>may</em> be caused by growth pains, but could have other prime causes. As an example, if a standup takes too long to run, it’s likely to be due to the team size, but it could be a very talkative team member uses 10 minutes everyday.</p><h4>Warnings your team is a small size team</h4><p>Likely you wouldn’t be here if it’s the case :)</p><p>By exclusion, small teams will be teams that don’t exhibit the warnings of medium and large teams.</p><h4>Warnings your team is a medium size team</h4><ul><li>Not everyone is interested in what’s going on. For instance, a grooming session goes over tickets where part of the team are uninterested as they know they won’t work on them.</li><li>Crowded ceremonies.</li><li>Reaching an agreement is difficult (many opinions to align).</li><li>People start specialising in an area of the codebase, creating knowledge silos within the team.</li><li>The team doesn’t fit in a small meeting room.</li><li>Long stand-ups, sometimes overrunning.</li></ul><h4>Warnings your team is a large size team</h4><ul><li>Warnings for the medium sized teams</li><li>Feeling of too many things happening at the same time</li><li>Lots of communications about specifics</li><li>Lots of ad-hoc syncs to get everyone on the same page</li><li><a href="https://www.youtube.com/watch?v=haejb5rzKsM&amp;feature=emb_title">Teams cognitive load overwhelmed</a>. This imbues the team in a mist of stress where somethings maybe being forgotten or missed as there’s too many plates to juggle.</li><li>Deadlocks in decision making.</li><li>Little common ground in retros.</li><li>Typing attendees to meetings takes longer than summarising the outcome.</li><li>Team doesn’t fit in a large meeting room.</li><li>Often people don’t do something cause they wait on someone else to do something first</li><li>Stand-ups consistently overrun.</li></ul><h3>Recommended actions depending on team size</h3><h4>Small team</h4><p>A small team should be lean and nimble. At this early stages, simplicity should be favoured to avoid committing too much effort future proofing something that may never occur. As a result, we would recommend to:</p><ul><li>Avoid overly modular architecture as it requires an overhead to plan, execute, and maintain.</li><li>Keep It Simple, Stupid.</li><li>Focus your unit test code coverage on business logic that warrants those tests.</li></ul><p>As your team grows, you can start easing in more overhead to keep everything ticking along.</p><h3>Medium team</h3><p>At this stage, you’ll likely be dubitative on “Should we take action now, split the team, and risk storming for a period while we get used to it, or carry on as is?”.</p><p>Unfortunately, we can’t clear your doubts. As everything, splitting the team will have a tradeoff, so ensure you have a clear understanding of them via a cost/benefit analysis.</p><p>Be clear on what would it cost to act now, versus how much benefit we’d get. Also, don’t just think about this cost/benefit as a static one off, but consider how will it evolve over time. Will cost go down while benefit remains constant? Will cost go up? That should factor into your decision to act.</p><p>Finally, never forget about <a href="https://www.investopedia.com/terms/o/opportunitycost.asp">opportunity costs</a>. You could use that same time on something more beneficial to the company.</p><h3>Large team</h3><p>If you have concluded that your team is a large one, then you have to find a way to split it apart, creating multiple small teams that recover the initial ability to be lean and nimble, but now at scale.</p><h4>Splitting teams</h4><p>Splitting teams is not an easy feat, but we’ll try to summarise what you should have in mind while doing it.</p><p>The main goal when you split teams is to enable them to act as decoupled teams, that is:</p><ul><li>Each sub-team should look like a complete small software organisation.</li><li>The internal processes and communication of the team should not be a concern outside the team.</li><li>How the team implements software should not be important outside the team.</li><li>Teams should communicate with the wider organisation about external concerns: common protocols, features, service levels and resourcing.</li></ul><p>To achieve that, there’s three main dimensions where the team split will impact your team members. For each of them, you should be able to understand:</p><p><strong>Who will they work with?</strong></p><p>The first one should be somewhat simple, as it would be listing the new teams composition.</p><p><strong>What will they work on?</strong></p><p>What will they work on is where it gets a bit more convoluted. Will they work on a specific feature? What will happen once that feature is done? Will this team lose its meaning? Will they work on maintenance?</p><p>There’s no absolute answer for this question, so you’ll have to consider what alternatives are in your reach and plan out how the next few months of the team will look like. A good resource to think of what a team can work with is <a href="https://teamtopologies.com/">Team topologies</a> which calls out the multiple ways teams can collaborate to achieve a common goal.</p><p><strong>Where will they work within the codebase?</strong></p><p>Finally, where will the new teams work within the codebase. Will they overlap modifying the same files and creating merge conflicts?</p><p>In order to maximise the performance of a decoupled team, the architecture they work on has to similarly be also decoupled. In <em>“Accelerate, the science of lean software and dev-ops independent teams”</em>, they define a decoupled architecture as one where you can:</p><ul><li>Make large-scale changes to the design of their system without the permission of somebody outside the team.</li><li>Make large-scale changes to the design of their system without depending on other teams to make changes in their systems or creating significant work for other teams.</li><li>Complete their work without communicating and coordinating with people outside their team.</li><li>Deploy and release their product or service on demand, regardless of other services it depends upon.</li><li>Do most of their testing on demand, without requiring an integrated test environment.</li><li>Perform deployments during normal business hours with negligible downtime.</li></ul><p>The first likely blocker you’ll find on this comes from Conway’s law:</p><blockquote><em>Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.</em></blockquote><blockquote><em>— Melvin E. Conway</em></blockquote><p>As your team has been so far a single unit designing a system, in all likelihood, you’ll have a monolithic system or component to share amongst multiple teams, and therefore, you won’t have a decoupled architecture.</p><p>The first step towards having a decoupled architecture will come from applying an Inverse Conway manoeuvre, which consists on hacking Conway’s law, and start creating the architecture that will enable your future team structure to work efficiently. This can be performed early on in the team’s lifecycle, but consider it will come with an overhead cost in planning and executing the layer separation required.</p><h4>Summary</h4><p>In summary, scaling a software engineering team can be a time consuming endeavour, but when executed properly, you have the chance to multiply the velocity of your company by horizontally scaling the number of engineers you work with.</p><p>In order to do so, you have to carefully plan the team structure so that your teams remain decoupled, and create a new architecture that scales to a larger number of developers.</p><p>You’ll also find yourself in an awkward phase where you are on the verge of needing to split the team, but not fully there. A cost/benefit analysis that considers how the tradeoffs will evolve over time will help guide your decision to act early or not.</p><h4>Further reading</h4><ol><li><a href="https://mikehadlow.blogspot.com/2018/11/decoupling-architecture-and-teams.html">https://mikehadlow.blogspot.com/2018/11/decoupling-architecture-and-teams.html</a></li><li><a href="https://www.scrumexpert.com/knowledge/when-is-a-scrum-team-too-big/">https://www.scrumexpert.com/knowledge/when-is-a-scrum-team-too-big/</a></li><li><a href="https://www.toptal.com/product-managers/agile/scrum-team-size">https://www.toptal.com/product-managers/agile/scrum-team-size</a></li><li><a href="https://mikehadlow.blogspot.com/2018/11/decoupling-architecture-and-teams.html">https://mikehadlow.blogspot.com/2018/11/decoupling-architecture-and-teams.html</a></li><li><a href="https://www.forbes.com/sites/meehanjonker/2018/05/30/team-of-teams-an-emerging-organizational-model/">https://www.forbes.com/sites/meehanjonker/2018/05/30/team-of-teams-an-emerging-organizational-model/</a></li><li><a href="https://teamtopologies.com/">https://teamtopologies.com</a> <a href="https://itrevolution.com/team-cognitive-load-team-topologies/">https://itrevolution.com/team-cognitive-load-team-topologies/</a></li><li><a href="https://medium.com/@beaugordon/key-takeaways-from-team-of-teams-by-general-stanley-mcchrystal-eac0b37520b9">https://medium.com/@beaugordon/key-takeaways-from-team-of-teams-by-general-stanley-mcchrystal-eac0b37520b9</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654fd1a98fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leaky abstractions lead to implicit coupling]]></title>
            <link>https://medium.com/@josep.rodriguez/leaky-abstractions-lead-to-implicit-coupling-fd05275244c?source=rss-b5fea64e704b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd05275244c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Josep Rodriguez]]></dc:creator>
            <pubDate>Sun, 24 Jun 2018 17:34:24 GMT</pubDate>
            <atom:updated>2018-06-24T17:34:24.521Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>In this post we’ll try to raise the risks of implicit coupling created by leaky abstractions, and how this can be mitigated (in some cases) with a stronger contract that better seals the leaks of the abstraction. Let’s go first into the basics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*v-iO347M9pLLTj175RI3PQ.jpeg" /><figcaption>Avoid leaking information in your code!</figcaption></figure><h3>Coupling</h3><p><a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">Coupling</a> is according to Wikipedia:</p><blockquote>[…] the degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules</blockquote><p>Any code ever written will be coupled to other modules, be it the framework we are building upon (Java, C++ std libs, …), or modules we have built on our own (other classes, libraries,…).</p><h3>Abstraction</h3><blockquote>the quality of dealing with ideas rather than events.</blockquote><p>In Software Engineering, an abstraction provides a simple interface to interact with a more complex module, to solve a problem we have.</p><p>It can be either a protocol (HTTPS, TCP, GraphQL,…) or an interface (command line interfaces such as mkdir, an interface you write in your code, printf,…).</p><p>The main benefit of this is to enable us to compose and build on top of other modules, while loosely coupling to them.</p><h3>Leaky abstractions</h3><p>A <a href="https://en.wikipedia.org/wiki/Leaky_abstractio">leaky abstraction</a> can be understood as an abstraction that fails to abstract away all its concerns, forcing the consumers to also have to consider its limitations.</p><p>Consider using an ORM, only to find that doesn’t support cascade-deleting records. You’ll have to roll out your own cascade-delete mechanism.</p><p>Another example is failing to resolve the hostname via DNS when using HTTP. Despite dealing with a higher level of abstraction, we still are affected by underlying network conditions, and have to consider what impact they could have on our codebase.</p><blockquote>All non-trivial abstractions, to some degree, are leaky.</blockquote><h3>Implicit coupling</h3><p>When it comes to Computer Science, coupling is often measured in how many references to one module the module we are working with has. In order to lower the coupling between modules, following the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency inversion principle</a>, we will produce code similar to the following:</p><pre>public interface Logger {<br>  void log(String message);<br>}</pre><pre>public class ConsoleLogger implements Logger {<br>  public void log(String message) {<br>    System.out.println(message);<br>  }<br>}</pre><pre>public class MyClass {<br>  private Logger logger;<br>  //..</pre><pre>  void myMethod() {<br>    logger.log(&quot;Hello world!&quot;);<br>  }<br>}</pre><p>Following this pattern, we decouple MyClass from System.out.println and the ConsoleLogger by introducing an abstraction, the Logger interface, which will allow us to change the implementation without the consumer being affected.</p><p>Then again, what happens if we are decoupling with a leaky abstraction?</p><p>Let’s compare two different abstractions aiming to provide an API client listener for consumers to manage network errors.</p><p><strong>Example 1:</strong></p><pre>public interface APIClientListener {<br>  ...<br>  void didFail(Exception exception);<br>}</pre><p>In the first example, we are calling our listener with a generic Exception type. This keeps the implementors of this abstraction decoupled from the APIClient. However, when we have to consume this interface, we will have to consider “In what ways will the APIClient fail?”, and this abstraction will offer no help.</p><p>The developer will have to look into the APIClient implementation, and study how errors are handled, and in what way they are thrown. Since we are using a generic Java Exception, it’s likely that we will also need to study what the dependencies the APIClient depends upon in order to be certain of what the different error scenarios will be.</p><p>The outcome of this work will be an integration with APIClient that contains a set of assumptions. When we change the behaviour of APIClient, we will have to consider how all consumers expect us to behave, otherwise we’ll risk introducing bugs as we break the assumptions the consumers built upon.</p><p><strong>Example 2:</strong></p><pre>public enum APIClientError {<br>  UNAUTHORIZED, NOT_FOUND, NO_CONNECTIVITY<br>}</pre><pre>public interface APIClientListener {<br>  ...<br>  void didFail(APIClientError error);<br>}</pre><p>In this example we have strengthened the contract offered by APIClient to consumers by defining an enum with the different kinds of errors the APIClient can raise.</p><p>When we consume this APIClient, all the investigation we had to do to understand how it manages errors will not be required, nor any assumptions will need to be made.</p><p>When we update our APIClient, we won’t need to think what the consumers assumptions from the APIClient are, since they are clearly documented in the exposed API.</p><p>This results in both APIClient and its consumers being able to change independently without having to think too much about each other.</p><h3>Summary</h3><p>In summary, by using leaky abstractions, we will introduce coupling between the modules we are trying to decouple.</p><p>This coupling won’t be made explicit in our codebase through dependencies such as an import/include/require, or a use of a type.</p><p>Instead, this coupling will be present <em>implicitly </em>as a set of assumptions on how the abstraction we are decoupling should work.</p><p>These assumptions will force us to have to consider many modules at once when working on our codebase so as to avoid breaking them, introducing new bugs on our system.</p><p>Having to consider many modules at once will make our system more complex.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/kenscambler/status/1008657233452810240&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fprofile_images%252F1004915058084704256%252FGKvyHfqx_400x400.jpg%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="185" frameborder="0" scrolling="no"><a href="https://medium.com/media/107b3c2232d173f7f46595ebaf210fe0/href">https://medium.com/media/107b3c2232d173f7f46595ebaf210fe0/href</a></iframe><p>In order to avoid implicit coupling, create a stronger contract between the abstraction and consumer by modeling into your code the behaviour that both must comply with. Some of the usual ways:</p><ul><li>If an action can be cancelled, offer in your abstraction a way to do so.</li><li>If multiple error scenarios can occur, ensure there’s an enumeration of what errors could occur.</li><li>When both sides of the abstraction are owned by you, build a common domain model. That is, prefer a Person class overString name, String surname, int age parameters.</li><li>Avoid <a href="http://wiki.c2.com/?StringlyTyped">stringly typed</a> interfaces.</li><li>If you are throwing exceptions, use types you own.</li><li>If your language doesn’t support checked exceptions, prefer to pass an error enum, preferably in an <a href="https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/10_Error_Handling#the-either-monad">Either</a> monad.</li></ul><h3>References</h3><p><a href="https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/">The Law of Leaky Abstractions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd05275244c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internals of Android Architecture Components Part II— LiveData]]></title>
            <link>https://medium.com/the-lair/internals-of-android-architecture-components-part-ii-livedata-a26a4d11795?source=rss-b5fea64e704b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26a4d11795</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Josep Rodriguez]]></dc:creator>
            <pubDate>Sun, 27 May 2018 20:14:27 GMT</pubDate>
            <atom:updated>2018-06-16T10:08:59.331Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>This post series explores the implementation of <a href="https://developer.android.com/topic/libraries/architecture/"><em>Android Architecture Components</em></a><em> </em>(AAC) so we <a href="https://8thlight.com/blog/uncle-bob/2015/08/06/let-the-magic-die.html">make the magic go away</a>. In this instalment we’ll focus on LiveData. You can see the other posts here:</p><ol><li><a href="https://medium.com/@josep.rodriguez/internals-of-android-architecture-components-part-i-the-viewmodel-d893e362a0d9">The ViewModel</a></li><li><a href="https://medium.com/@josep.rodriguez/internals-of-android-architecture-components-part-ii-livedata-a26a4d11795">LiveData</a></li></ol><h3>What is LiveData?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vN7l-t-bVaHqZVv6." /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s look at the definition from <a href="https://developer.android.com/topic/libraries/architecture/livedata">Android’s documentation</a>:</p><blockquote><a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html"><strong>LiveData</strong></a><strong> is an observable data holder class</strong>. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.</blockquote><p>In summary:</p><ul><li>LiveData follows the <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a>, notifying subscribers of new data being available.</li><li>LiveData is Lifecycle aware, which means that it will notify subscribers only when it’s in an active lifecycle state, and it will dispose the subscription when the Lifecycle terminates and is destroyed.</li></ul><h3>How does LiveData implement the Observer pattern?</h3><p>Now that we have a brief introduction to the concept, let’s look at how it implements the Observer pattern.</p><p>The following snippet is how LiveData is expected to be consumed, as specified by Android’s documentation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172874d8ab27e65fb8401a6b27d14643/href">https://medium.com/media/172874d8ab27e65fb8401a6b27d14643/href</a></iframe><p>First, the ViewModel creates a MutableLiveData and exposes it. Then, the Activity will consume it by creating an Observer, and calling .observe(this, nameObserver).</p><p>Diving into observe, we can see how it manages the subscriptions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6227da7ab9c65d561ebcabb3c993be6d/href">https://medium.com/media/6227da7ab9c65d561ebcabb3c993be6d/href</a></iframe><p>The first thing we notice is that observe depends on a LifecycleOwner and the Observer instance we create. When the lifecycle is not in the DESTROYED state, observe creates a LifecycleBoundObserver instance using the LifecycleOwner and the Observer.</p><p>After ensuring we don’t add twice the same Observer with different LifecycleOwners, it sets the wrapper to listen for Lifecycle events.</p><p>Now that we know how subscription works, let’s look at how the notification of observers is executed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab96e01f78096fa919a29040ef137d48/href">https://medium.com/media/ab96e01f78096fa919a29040ef137d48/href</a></iframe><p>Setting the value is rather straight forward. LiveData will assert we are on the main thread, update mData to hold the latest data, and notify the observers.</p><p>In dispatchingValue we can see that it will invalidate a previous dispatch if needed, and iterate the observers using considerNotify where:</p><ul><li>It checks that the lifecycle is active.</li><li>It checks that the version dispatched is newer than the last version received.</li><li>Calls onChanged with the data we are setting.</li></ul><p>We’ll revisit later how considerNotify won’t post the event if the Lifecycle is not active, and as a note; postValue is able to dispatch new data from any thread in a safe manner, but this is outside of the scope of this article.</p><h3>How doesLiveData become Lifecycle aware?</h3><p>As we disovered from <a href="https://proandroiddev.com/internals-of-android-architecture-components-part-i-the-viewmodel-d893e362a0d9">the first post of this series</a>, the ViewModel will be reused while the Activity is destroyed and recreated, and LiveData will continue to work undisturbed by events such as screen rotations and backgrounding the app.</p><p>When we looked at how the LiveData is observed, we noticed that a LifecycleBoundObserver is created by wrapping the real observer and the LifecycleOwner.</p><h4>Disposing the subscription</h4><p>When the Activity or Fragment is destroyed, the subscription will have to be automatically disposed. Let’s look into how it’s achieved by looking at the LifecycleBoundObserver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77c18a256e30163ad62e25ddc7e63f5c/href">https://medium.com/media/77c18a256e30163ad62e25ddc7e63f5c/href</a></iframe><p>In the implementation we can see:</p><ul><li>shouldBeActive actively checks the Lifecycle state of the owner</li><li>onStateChanged will remove this from the observer list when the DESTROYED state is reached. This allows to create the observer in onCreate without having to worry about unsubscribing or disposing of it in any other way in onDestroy.</li></ul><p>Finally, how does Activity implement LifecycleOwner and when is it tagged as DESTROYED?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f275cf937400eb8614fe52ab44e4d4c/href">https://medium.com/media/7f275cf937400eb8614fe52ab44e4d4c/href</a></iframe><p>The first thing we can see is that SupportActivity uses a LifecycleRegistry as the instance of Lifecycle, and that this is passed into the constructor. Our guess is that LifecycleRegistry will be listening to Activity state changes in it, however it seems to be doing so in a somewhat obscure way. We’ll resort to using a breakpoint in onStateChanged to inspect the stack trace of callers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hf-YlzLIHpfbMVHI1f-_lQ.png" /><figcaption>When the control flow is not clear enough, a breakpoint is your friend.</figcaption></figure><p>Browsing the stack trace, we can see that the events are sent from a ReportFragment instance.</p><p>The ReportFragment is injected in the Activity in onCreate, and behaves as a headless Fragment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a28120805937888caf954b10330ad5f/href">https://medium.com/media/8a28120805937888caf954b10330ad5f/href</a></iframe><h4>Delaying notifications on non-active Lifecycle state</h4><p>Remember how considerNotify didn’t post the events when the Lifecycle is inactive? Let’s look at how we recover the data when the Lifecycle becomes active again.</p><p>The key is in LifecycleBoundObserver where onStateChanged calls activeStateChanged, implemented in ObservableWrapper, to re-submit the latest value when it becomes active again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d3cdec7a430f9075f21e40cce1ff21/href">https://medium.com/media/32d3cdec7a430f9075f21e40cce1ff21/href</a></iframe><h3>Summary</h3><ul><li>LiveData proposes an Observer pattern as a solution to simplify how to pass data to components across their lifecycle.</li><li>LiveData will always dispatch events to the main thread.</li><li>LiveData builds upon the Lifecycle AAC.</li><li>Any object implementing LifecycleOwner can be used withLiveData. Most of the time you’ll be using Activity/Fragment/Service which already implement it for you.</li><li>LiveData will not deliver values while the Lifecycle is inactive (e.g. paused), and will submit as soon as the Lifecycle becomes active again (e.g. resumed).</li><li>LiveData simplifies LifecycleOwner by automatically disposing observers when the DESTROYED event is triggered in the lifecycle.</li><li>On SupportActivity (and all subclasses) Android uses yet again a headless Fragment to split responsibilities. In this case, ReportFragment is used to dispatch lifecycle events to observers.</li><li>android.support.v4.app.Fragment dispatches the events on the performXYZ() methods, where XYZ is a lifecycle event.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26a4d11795" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-lair/internals-of-android-architecture-components-part-ii-livedata-a26a4d11795">Internals of Android Architecture Components Part II— LiveData</a> was originally published in <a href="https://medium.com/the-lair">The Alchemy Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internals of Android Architecture Components Part I — The ViewModel]]></title>
            <link>https://medium.com/the-lair/internals-of-android-architecture-components-part-i-the-viewmodel-d893e362a0d9?source=rss-b5fea64e704b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d893e362a0d9</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Josep Rodriguez]]></dc:creator>
            <pubDate>Sun, 20 May 2018 08:21:04 GMT</pubDate>
            <atom:updated>2018-06-16T10:08:24.999Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYabs9UmGucX5joGvgB6mA.jpeg" /></figure><p>On this post series I’ll try to shed light on how <a href="https://developer.android.com/topic/libraries/architecture/"><em>Android Architecture Components</em></a><em> (AAC) </em>work in order to better leverage them, starting on the <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel">ViewModel</a>.</p><p>You can see the other posts here:</p><ol><li><a href="https://medium.com/@josep.rodriguez/internals-of-android-architecture-components-part-i-the-viewmodel-d893e362a0d9">The ViewModel</a></li><li><a href="https://medium.com/@josep.rodriguez/internals-of-android-architecture-components-part-ii-livedata-a26a4d11795">LiveData</a></li></ol><h4>Why should we understand how AAC works?</h4><p>First of all, let’s cover the motivation for this series. I consider best practice to decouple the logic of your application from the platform it runs upon (see <a href="http://alistair.cockburn.us/Hexagonal+architecture"><em>Ports and Adapters</em></a>), that involves decoupling it from any API it may consume, the storage solutions (SQLite, Realm, SharedPreferences, the file system,…), and more importantly, the Android runtime.</p><p>Some of the reasons to it is that:</p><ol><li>Platform dependencies will hamper the testability of your solution, making it either harder to unit test, slower, or impossible.</li><li>The platform dependencies will evolve over time, outside of your control. A change on these dependencies, should not imply a change on your business logic. This is driven by the <em>Single Responsibility Principle</em> (a class should have a single reason to change), and the <a href="https://en.wikipedia.org/wiki/Package_principles"><em>Stable Dependencies Principle</em></a><em> </em>(a package should depend on packages less likely to change than itself).</li></ol><p>With AAC, Google is offering a set of libraries that drive Architectural decisions that target the business logic of your app, but at the same time, coupling it onto the Android SDK.</p><h3>What are the AAC ViewModels?</h3><p>On <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">Android’s documentation page</a> it states that ViewModels can be used to keep …</p><blockquote><em>“Store UI-related data that isn’t destroyed on app rotations.”</em></blockquote><p>But how does it manage to do so? Let’s reveal the magic tricks.</p><h3>How AAC ViewModels are retained across configuration changes</h3><p>First, let’s visit the Android documentation to see how the ViewModel is consumed. The following code is the example of how a Fragment uses the SDK in order to provide a ViewModel that is retained on configuration changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a195854cc52d127b081d6d51ced06e4/href">https://medium.com/media/8a195854cc52d127b081d6d51ced06e4/href</a></iframe><p>The line we want to focus on right now is:</p><blockquote><em>ViewModelProviders.of(this).get(MyViewModel.class);</em></blockquote><p>we can infer that it’s retrieving a ViewModel of type MyViewModel. Let’s look into how each of these methods work, starting with ViewModelProviders.of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03aa4fe2149effcb4e508e139b85ce8b/href">https://medium.com/media/03aa4fe2149effcb4e508e139b85ce8b/href</a></iframe><p>It looks like <em>ViewModelProviders.of</em> is just a factory of ViewModelProvider, who depends upon a ViewModelStore and a ViewModelFactory. We’ll have to dig deeper to fully understand how ViewModels<em> </em>work.</p><h4>The ViewModelStore</h4><p>If we look into the dependencies, the ViewModelStore seems to be a simple store with a HashMap&lt;String, ViewModel&gt;, where the key is the classname of the view model and the Object the ViewModel itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50a2962df79ed5b11a5f4e19ba22b29d/href">https://medium.com/media/50a2962df79ed5b11a5f4e19ba22b29d/href</a></iframe><h4>ViewModelFactory</h4><p>On the other hand, the ViewModelFactory is using reflection to instantiate the ViewModel we need. The AndroidViewModelFactory used in ViewModelProviders.of overrides a generic ViewModelFactory in order to provide a reference to the Application Context to the ViewModel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b5a801107064c4365c0ccaef054188a/href">https://medium.com/media/8b5a801107064c4365c0ccaef054188a/href</a></iframe><p>If the ViewModel class is of type AndroidViewModel, then it will create a new instance passing the application as a single parameter in the constructor, otherwise, it calls the parent implementation, which is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8949140808c459cbd3900603c3272d98/href">https://medium.com/media/8949140808c459cbd3900603c3272d98/href</a></iframe><p>This is a simple factory implemented via reflection that provides no arguments to the ViewModel object.</p><h4>How it all ties together</h4><p>Now that we understand the ViewModelProvider creation and its dependencies, we will look into how it creates and retrieves theViewModel instances,<em> </em>retaining them throughout configuration changes. Let’s look into the get(MyViewModel.class) method call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db2e71871f69bd03a5a42aefcd8145a/href">https://medium.com/media/0db2e71871f69bd03a5a42aefcd8145a/href</a></iframe><p>This works as one would expect, it tries to retrieve a ViewModel from the store, if none is there, it uses the factory to create it and stores it. In order to retrieve the already created ViewModel, it generates a key from the class qualified name.</p><h4>Surviving configuration changes</h4><p>So far we’ve seen how the ViewModelStore is the object responsible to keep the references of ViewModel to be reused, but how is the ViewModelStore surviving configuration changes itself? Let’s go back to the implementation of ViewModelProviders.of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79259fb2f83a210f92c4144d734b93cf/href">https://medium.com/media/79259fb2f83a210f92c4144d734b93cf/href</a></iframe><p>ViewModelStores.of seems to be a similar method to ViewModelProviders.of, creating new instances of the ViewModelStore as required. Let’s look into how this is implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf18079c08c03bc0512aae3eb9ea855d/href">https://medium.com/media/bf18079c08c03bc0512aae3eb9ea855d/href</a></iframe><p>Apparently, we can provide the ViewModelStore in three ways:</p><ul><li>Using the android.support.v4.app.Fragment which implements ViewModelStoreOwner.</li><li>Implementing ViewModelStoreOwner in our Fragment, and owning the responsibility of creating and disposing the store.</li><li>Let AAC create a HolderFragment, who already implements ViewModelStoreOwner, and the AAC library and Android SDK will do the heavy lifting.</li></ul><h4>How HolderFragment retains the state</h4><p>This raises the question of what is a HolderFragment and how it maps to our Fragment stack. Let’s look now at how holderFragmentFor(Fragment) works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8678ac2ac698b9748f3cae8729f7c0ae/href">https://medium.com/media/8678ac2ac698b9748f3cae8729f7c0ae/href</a></iframe><p>The HolderFragment has a couple of ways of looking for the HolderFragment<em> </em>associated with your<em> </em>Fragment, and if not found, it will create new HolderFragment and add it on the FragmentManager of our own Fragment. Now, how does this fragment in our stack survive rotation changes while the rest of the fragments die in their regular lifecycle? The answer is in the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/007bef9e0241b90cb69ff9bec44e9597/href">https://medium.com/media/007bef9e0241b90cb69ff9bec44e9597/href</a></iframe><p>By setting retain instance to true and not providing a view, the HolderFragment becomes essentially a headless Fragment that is retained for as long as the Activity is not destroyed.</p><h4>How android.support.v4.app.Fragment retains state</h4><p>On the other hand, if you opt for using the support Fragment, the state will be retained, however it becomes more complex to follow the code that manages it.</p><p>In order to understand the flow of control of this classes, we looked at the onDestroy method of the Fragment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc3a7161b1929675be87d6aea4ae169/href">https://medium.com/media/5dc3a7161b1929675be87d6aea4ae169/href</a></iframe><p>The condition to call clear on the ViewModelStore is that mHost.mFragmentManager.mStateSaved is false.</p><p>By adding a breakpoint on the mStateSaved instance variable we managed to identify when it is set to true, and by whom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWzFN0rH4YkO7PEUwo6S5A.png" /><figcaption>Isn’t Android’s code “beautiful”?</figcaption></figure><p>By navigating the resulting stack trace, we end up on discovering that the FragmentManager.saveAllState method is called by FragmentActivity.onSaveInstanceState.</p><h3>Summary</h3><p>To summarise, the reasons it is able to create and retain the ViewModel are:</p><ol><li>A ViewModelProvider creates with Reflection the ViewModel with a ViewModelFactory.</li><li>A ViewModelProvider retains the ViewModel across configuration changes with a ViewModelStore, provided by a ViewModelStoreOwner, this can be done with a HolderFragment, leveraging android.support.v4.app.Fragment or implementing our own.</li><li>An android.support.v4.app.Fragment will use the FragmentManager.saveAllState as called by FragmentActivity.onSaveInstanceState to retain the ViewModelStore using theflag mStateSaved on onDestroy.</li><li>A HolderFragment is a headless Fragment (without UI) that is added to the <em>Fragment</em> stack with setRetainInstance(true).</li></ol><h3>References</h3><p>Other sources that go into more depth onto how AAC works in depth are:</p><ul><li><a href="https://medium.com/google-developer-experts/viewmodels-under-the-hood-f8e286c4cc72">ViewModels under the hood..</a></li><li><a href="https://medium.com/@Viraj.Tank/android-architecture-components-viewmodel-internals-should-you-use-it-for-mvps-presenter-6bf7b770cf12">Android Architecture Components — ViewModel Internals &amp; Should you use it for MVP’s Presenter?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d893e362a0d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-lair/internals-of-android-architecture-components-part-i-the-viewmodel-d893e362a0d9">Internals of Android Architecture Components Part I — The ViewModel</a> was originally published in <a href="https://medium.com/the-lair">The Alchemy Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>