<?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 Lucia Payo on Medium]]></title>
        <description><![CDATA[Stories by Lucia Payo on Medium]]></description>
        <link>https://medium.com/@LuciaP_86?source=rss-d866ff513d08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7LBHLPgqcPpX_leHmokbZw@2x.jpeg</url>
            <title>Stories by Lucia Payo on Medium</title>
            <link>https://medium.com/@LuciaP_86?source=rss-d866ff513d08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 19:26:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LuciaP_86/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[Four principles for software engineering]]></title>
            <link>https://medium.com/@LuciaP_86/four-principles-for-software-engineering-7b9858e9652d?source=rss-d866ff513d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9858e9652d</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Lucia Payo]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 09:40:01 GMT</pubDate>
            <atom:updated>2022-02-23T09:31:57.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjCSopxjanDqgGKHiPEN4g.jpeg" /></figure><p>At <a href="https://exakthealth.com/">exakt health</a> we aim to create a healthy and sustainable engineering culture. In this article, I want to talk about the principles that help us create this culture. These four principles are not only good for the software that we build, but they also put the people that build it in the center. The goal is to deliver the best solutions while keeping the team&#39;s motivation and happiness high. We do this by reducing barriers as much as possible and investing in things that make us feel productive and in control. In our view, this is the only way to have a healthy and sustainable tech culture that also delivers a product with high standards.</p><h3>Readability</h3><p>The goal of readability is to make everything we create as easy as possible for another person to read and understand. This goes from the code, to the documentation, to anything that needs to be used and maintained. Readability is at the core of many other engineering good practices, it&#39;s people who work and maintain the codebases, so the easier it gets for us to understand, the more efficient we work and the fewer issues we introduce.</p><p>Readability should be at the top of our principles and not be compromised unless doing so makes us fail to deliver the product and quality requirements. For instance, let’s say we can improve the performance of some functionality by sacrificing readability. In this case, we need to confirm first the impact of this performance improvement, is it really necessary? If it is, performance becomes a requirement. The original code doesn’t deliver the performance requirement so we need to write this logic differently to accommodate the level of performance we want in the most readable way possible. On the other hand, if we don’t have objective and, preferably, measurable reasons to think that there is an issue with performance worth solving, we should not sacrifice readability. We are leveraging the machine’s power so the code is easier to work with, which is fine.</p><blockquote>Writing readable code is the second most important goal of a developer, only after writing code that does what is meant to do.</blockquote><p>But, what are the characteristics of readable code? There is plenty of material about this topic, here I leave two of my favorite articles:</p><ul><li><a href="https://blog.pragmaticengineer.com/readable-code/">Readable Code</a> by Gergely Orosz</li><li><a href="https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c">Clean Code 101</a> by Miguel Loureiro</li></ul><h3>Simplicity</h3><p>This principle is about solving the problem at hand in the most concise way possible. Simplicity also applies to everything we create as engineers, not just code, and goes hand in hand with readability. Similarly to readability, we should keep simplicity at the top of our principles and only make our code more complex when the problem we are trying to solve becomes intrinsically more complex.</p><p>We are lucky to work in an industry where people share their experiences and work selflessly, making software development rich in architectures, practices, frameworks, libraries, etc. Thanks to this, we have a lot of options to choose from, but even though it is important to know what are the possibilities, it is even more important to know what to use when.</p><p>Every time we introduce a new framework, architecture or library, the complexity of our code increases. This is a necessary evil, thanks to that we add layers of abstraction and we can solve more advanced problems, but there is a fine line between including something that will truly make us more productive and something that will create more problems than it solves. For instance, including a dependency injection library will help us decouple the creation of instances from the places where they are used, allowing us to abstract the actual implementation of the instance passed as long as it complies with a definition. This, by extension, makes our code easier to test, more flexible and loosely coupled. On the other hand, it can make instance creation — one of the most basic tasks — pretty obscure, putting a black box at the heart of our program. It will introduce a set of drawbacks that we’ll have to deal with forever after: learning curve, hard to debug problems, more difficult hiring/onboarding, etc. We need to carefully consider if using a library like that is worth it in our context or if we can get the same benefits — or the most important ones — with a simpler approach that might not require any external library.</p><blockquote>There are many practices, architectures and libraries available but all of them boil down to solving a much smaller set of common problems. Focusing on these bottom-line problems will help us choose the best tool for the job.</blockquote><p>The 80/20 rule — or Pareto principle — is a great way to weigh the different approaches. What this principle states is that, for many events, roughly 80% of the effects come from 20% of the causes. I think this principle applies very well to software engineering and it’s very useful when it comes to making decisions. It helps you to stay pragmatic and not fall into the rabbit hole of perfectionism.</p><p>For instance, It is common to have several ways to solve one problem. Usually, these ways range from fast and hacky to perfect in every detail. I believe picking the one closer to the 80/20 rule is a good approach: 80% of the value is produced by 20% of the effort and complexity. Then we can take the remaining 20% and apply the 80/20 rule again or decide the existing solution is good enough for the time. This way we can also deliver value consistently, instead of waiting until 100% is done.</p><h3>Automation</h3><p>Automation removes the mental weight of doing recurring tasks so we can focus on the important tasks at hand. The fewer things we focus on, the better we work. It’s very satisfying when we are creating value fast and safely, automation is a big ally in this field. Without it we are forced to:</p><ul><li>remember the details of how to do satellite tasks that are necessary but don’t add up to the value creation per se. Having to do the context switch to perform these tasks back and forth, not only takes time, but also takes energy and can be a big motivation killer.</li><li>spend time on something that an automated process can do much better, killing our productivity. Also, the risk of making mistakes is high, especially when our motivation goes down.</li></ul><p>Here are three things I consider are worth automating since the very beginning of a project:</p><ul><li>Testing — A very big part of development is trying out the software we create to make sure everything works as expected. Writing tests is automating the process of “making sure everything works as expected”. Not only we will be saving a lot of time in the future, but we will also offload a lot of information around what needs to be tested and how from our heads, making space for more relevant things.</li><li>Static Analysis — Having automatic checks for common smells, wrong formatting, etc. is a low-hanging fruit that will help us write better code and perform better code reviews since it allows us to focus on the logic.</li><li>Mobile Releases, deployments, etc. — For instance, mobile releases require a lot of steps: freeze code, build the production variant, sign with production key/certificates, upload the artifact to stores, upload mapping/dSYM files, etc. It’s also a sensitive operation, we don’t want to make mistakes, and it’s recurring, so perfect candidate for automation.</li></ul><p>But automation is not complete if we don’t automate also when these checks are triggered so we don’t forget to run them when they matter the most. For that, we can use pipelines, like a PR pipeline that makes sure unit tests and static analysis pass before asking for a review, or a release pipeline that triggers integration or UI tests and then goes through the release steps. GitHooks are also a good tool, for instance in exakt health we use a pre-commit GitHook to make sure the branch is named after a ticker number and automatically append the ticket number to every commit message. This way we can get more context about any change in the code if we need to in the future.</p><blockquote>By automating repetitive tasks we can excel at the things we can’t automate.</blockquote><p>One thing to keep in mind is that it is easy to overdo it with automation, that’s why it’s important to keep the simplicity principle in mind. We need to automate only those things that cause a real problem for us and remember the 80/20 rule. Done right, automation should organically grow with the complexity of the project and organization.</p><h3>Observability</h3><p>Observability is a very important element in making good decisions. Thanks to observability we can validate assumptions and know if something is working as expected. It helps us decide what to do and when to do it.</p><p>One of the hardest decisions in software development is to figure out what is the sweet spot for a solution or feature when it comes to requirements vs complexity. Is what we built good enough? Is it working as expected? Is it useful? Thanks to observability we can start with a simple solution and iterate from there. It’s like running experiments to gather data points that will help us evolve the solution from simplistic to excellent.</p><blockquote>Observability gives us the intel to pick the battles that are the most important.</blockquote><p>Humans are very good at making assumptions, it helps us move fast and not be paralyzed at every step we do. The downside of this skill is that we are wrong many times, furthermore, if we are not careful, we’ll develop big blind spots. To counteract this downside, the first thing we need to do is to acknowledge that it is highly probable that we made wrong assumptions, and then we need to identify where these assumptions are. Reflecting on these two questions can help with this process:</p><h4>1. How do we know we are building the right thing?</h4><p>From product features to developer productivity solutions, it is easy to overdo it or miss the point. Most of the time — if not all of the time — it is impossible to know what the perfect solution is. Acknowledging that we don’t always know what is best and we don’t have all the answers is key. This way we can think about how we are going to get the information to help us decide what to do before investing lots of effort and resources. There are two key moments when we should spend some time reflecting:</p><ul><li>Before engaging in a project or task — Make sure that the problem exists, is worth solving and is framed. Spending some time reflecting and gathering data can save a lot of time later. Not only because we may find out the problem doesn’t have as big of an impact as we thought, but even when the problem is worth solving, it’s very important to clearly define what is the goal we want to achieve so we don’t over-engineer. If we can put a measurable metric to this goal, the better.</li><li>Before delivering a solution — Think about what are the data points that could be extracted to validate that the solution is solving the problem. One common example is introducing analytics events in key points of the program before releasing it to the public.</li></ul><h4>2. How do we know if something is not working as expected?</h4><p>If we did the previous point well, we will have data points that give us insights on how well what we built is doing. This information will help us steer our decisions and priorities in the right direction. It is important to build a strategy to process this data and continuously observe it.</p><p>Also, from the tech side, we need to make sure the software we create doesn&#39;t have bugs. For instance, while coding, it is easy to fall into the trap of assuming the program cannot be in a certain state, even though this state is technically possible. We might be tempted to either completely ignore this case or write some code that does “nothing” since in our minds this case is impossible. If we do this repeatedly it’s just a matter of time and volume before our program will run into these “impossible” dead-ends. The worst part is that we won’t even know when they happen.</p><blockquote>In any system, if something can happen, it will happen. It’s just about time.</blockquote><p>Nowadays there are plenty of tools to track and raise alerts when something is not working as expected like crashlytics or performance tracking. Leveraging them as much as we can is one of the smartest things we can do to maintain our software.</p><h4>One important side note about observability</h4><p>The data we gather is a support element in our decision making but we are the ones putting all the pieces together to make the final call. Many times, the data is trivial and straight forward and it’s easy to make a good decision, but there will be times when the data is too narrow or even biased, only measuring a specific part for specific conditions. After all, it’s us, the masters of assumptions and biases, the ones designing and introducing the observability. For that reason, it is very important to maintain our critical thinking since 100% objective observability doesn’t exist.</p><p>If you reached this far, thanks for reading! Here are the four key messages of the article in a nutshell:</p><ul><li>Write code so someone without coding background could guess what it does.</li><li>Recognize when a solution is good enough for the time and situation so you can move on.</li><li>Let machines do the boring and repetitive tasks so you can focus on the fun and creative parts.</li><li>Take your time to observe and reflect before making decisions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9858e9652d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical example using Reactive Clean Architecture approach]]></title>
            <link>https://medium.com/insiden26/practical-example-using-reactive-clean-architecture-approach-8a2436ea76b4?source=rss-d866ff513d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2436ea76b4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Lucia Payo]]></dc:creator>
            <pubDate>Tue, 05 Sep 2017 12:13:36 GMT</pubDate>
            <atom:updated>2018-10-31T09:52:06.750Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post we explained the principles of the reactive clean architecture that we use in <a href="https://n26.com/?utm_source=magazine&amp;utm_medium=article&amp;utm_content=practical-example-using-reactive-clean-architecture-approach">N26</a>. In this post we are going to show how to apply it.</p><p><a href="https://mag.n26.com/reactive-clean-architecture-with-android-architecture-components-685a6682e0ca">Reactive Clean Architecture with Android Architecture Components</a></p><p>Let’s say we want to create a new feature in the app that shows a list of the credits drafts the user has. The code for this example can be found in this <a href="https://github.com/n26/N26AndroidSamples">repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*QooMpj1x2Qrvm4-_-s4EWA.png" /></figure><h3>Data</h3><p>This is the entry point of the feature, we need to get the data from some API and put it in the reactive store. Let’s see how this process looks like.</p><p><strong>1. Connect to API</strong></p><p>We use retrofit for the network calls, in this case the service looks like this:</p><pre>interface CreditService {<br><br>    @GET(&quot;credit/drafts&quot;)<br>    Single&lt;List&lt;CreditDraftRaw&gt;&gt; getCreditDrafts();<br>}</pre><p><strong>2. Setup the reactive store</strong></p><p>The following interface is used for the ReactiveStore:</p><pre>public interface ReactiveStore&lt;Key, Value&gt; {</pre><pre>    void storeSingular(@NonNull final Value model);</pre><pre>    void storeAll(@NonNull final List&lt;Value&gt; modelList);</pre><pre>    void replaceAll(@NonNull final List&lt;Value&gt; modelList);</pre><pre>    Flowable&lt;Option&lt;Value&gt;&gt; getSingular(@NonNull final Key key);</pre><pre>    Flowable&lt;Option&lt;List&lt;Value&gt;&gt;&gt; getAll();<br>}</pre><p>We are not going to show the actual implementation of the ReactiveStore in this post. A simple reactive store based on memory cache is implemented in the provided <a href="https://github.com/n26/N26AndroidSamples">repository</a>. As we said in the previous <a href="https://medium.com/@LuciaP_86/reactive-clean-architecture-with-android-architecture-components-685a6682e0ca">post</a>, there are many ways to implement this component depending on the use case, we are planning to bring more posts in the future to show different possible implementations, stay tuned!</p><p>So, assuming we have the ReactiveStore implemented and ready, we’ll need to instantiate aReactiveStore for the desiredKey and Value. In this case the Value is CreditDraft and the Key is the id of the specific CreditDraft, represented by a String. We use Dagger for dependency injection, this is how the resulting methods in the module would look like:</p><pre>@Provides<br>@Singleton<br>Store&lt;String, CreditDraft&gt; provideCache() {<br>    return new Cache&lt;&gt;(CreditDraft::id, <em>CACHE_MAX_AGE</em>);<br>}<br><br>@Provides<br>@Singleton<br>ReactiveStore&lt;String, CreditDraft&gt; provideReactiveStore(Store&lt;String, CreditDraft&gt; cache) {<br>    return new MemoryReactiveStore&lt;&gt;(CreditDraft::id, cache);<br>}</pre><p>The first method provides a classic memory cache, which takes a function to extract the Key from the values to store and the max age to indicate when the values should expire. The second method creates the ReactiveStore, it also takes a function to extract the Key from the values and the cache.</p><p><strong>3. Create the raw to safe entity mapper</strong></p><p>Now, looking at the previous code snippets, we can see that the getCreditDrafts() method from the CreditService is returning a list of CreditDraftRaw objects, while the ReactiveStore is designed to take CreditDraft objects. We should be storing the objects that come from the API in the store, but as we saw in the first <a href="https://mag.n26.com/reactive-clean-architecture-with-android-architecture-components-685a6682e0ca">blog post</a>, we don’t want to store these objects straight away, we should process them and do some sanity checks first. This is where the raw to safe entity mapper comes into play:</p><pre>class CreditDraftMapper implements Function&lt;CreditDraftRaw, CreditDraft&gt; {<br><br>    @Override<br>    public CreditDraft apply(CreditDraftRaw raw) {<br>        ....<br>    }<br>}</pre><p>CreditDraftRaw POJO has all its non primitive type parameters annotated with @Nullable since there is no guarantee that they’ll be present in the API’s response payload. In the other hand, CreditDraft has all its non-primitive type parameters annotated with @NonNull.</p><p>There are two ways of handling the presence of the parameters when it comes to the raw to safe mapping. The first one is when the parameter must be present in the raw entity for the feature to function. This is the case of the status for instance:</p><pre>@AutoValue<br>public abstract class CreditDraftRaw {</pre><pre>    @Nullable<br>    abstract String status();</pre><pre>}</pre><pre>@AutoValue<br>public abstract class CreditDraft {</pre><pre>    @NonNull<br>    abstract CreditDraftStatus status();</pre><pre>}</pre><p>We’ll check if the status is present in the CreditDraftRaw and throw a runtime exception if it’s not there. Also it will be mapped from String to enum for convenience.</p><p>The other way is when the presence of the parameter is optional, this means is fine when is not in the API’s payload, in which case the parameter will be parsed to Option&lt;Parameter&gt;. This is the case of the CreditRepaymentInfo:</p><pre>@AutoValue<br>public abstract class CreditDraftRaw {</pre><pre>    @Nullable<br>    abstract CreditRepaymentInfoRaw repaymentInfo();</pre><pre>}</pre><pre>@AutoValue<br>public abstract class CreditDraft {</pre><pre>   @NonNull<br>   abstract Option&lt;CreditRepaymentInfo&gt; creditRepaymentInfo();</pre><pre>}</pre><p><strong>4. The repository</strong></p><p>At this point we have all the necessary components for the data layer, we just need to put them together in the repository. Also, the repository is the interface to the upper layer, the only class that should be visible from the data layer with exception of the safe entities.</p><p>In this case the CreditDraftRepository takes the CreditService, the ReactiveStore&lt;String, CreditDraft&gt; and the CreditDraftMapper in its constructor.</p><pre>CreditDraftRepository(ReactiveStore&lt;String, CreditDraft&gt; store,<br>                      CreditService creditService,<br>                      CreditDraftMapper creditDraftMapper) {<br>    this.store = store;<br>    this.creditService = creditService;<br>    this.creditDraftMapper = creditDraftMapper;<br>}</pre><p>For this example we only need the <strong>Get</strong> and the <strong>Fetch</strong> methods:</p><pre>Flowable&lt;Option&lt;List&lt;CreditDraft&gt;&gt;&gt; getAllCreditDrafts() {<br>    return store.getAll();<br>}<br><br>Completable fetchCreditDrafts() {<br>    return creditService.getCreditDrafts()<br>                        .subscribeOn(Schedulers.<em>io</em>())<br>                        .observeOn(Schedulers.<em>computation</em>())<br>                        // map from raw to safe                                 <br>                        .flatMapObservable(Observable::<em>fromIterable</em>)<br>                        .map(creditDraftMapper)<br>                        .toList()<br>                        // put mapped objects in store<br>                        .doOnSuccess(store::replaceAll)<br>                        .toCompletable();<br>}</pre><p>The <strong>Get</strong> is fairly simple, it’s the store’s stream from getAll() method with no mappings or modifications. The <strong>Fetch, </strong>in the other hand, requires a little bit more of work. When the List&lt;CreditDraftRaw&gt; comes from the API call, first we need to map them to List&lt;CreditDraft&gt;, which are going to be put in the store as next step. Finally, the Single observable is transformed to Completable.</p><blockquote>But why toCompletable()? Why not simply return the fetched values as Single&lt;List&lt;CreditDraft&gt;&gt;?</blockquote><p>The fetchCreditDrafts() is feeding the reactive store, this means the fetched values are going to be emitted in the Flowable from the getAllCreditDrafts() method. This is the concept behind this type of architecture, there is the stream that provides infinite updates of a specific value’s state and there is the action that feeds this stream, they are separate from each other.</p><p>Of course we don’t always need a store for the values, that’s why we have the <strong>Request </strong>method. For instance, if we don’t want to put the fetched List&lt;CreditDraft&gt; the resulting method would look very similar to the fetchCreditDrafts() from before but it won’t have the last two steps that puts the results to the store and converts it to Completable:</p><pre>Single&lt;List&lt;CreditDraft&gt;&gt; requestCreditDrafts() {<br>    return creditService.getCreditDrafts()<br>                        .subscribeOn(Schedulers.<em>io</em>())<br>                        .observeOn(Schedulers.<em>computation</em>())<br>                        .flatMapObservable(Observable::<em>fromIterable</em>)<br>                        // map from raw to safe<br>                        .map(creditDraftMapper)<br>                        .toList();<br>}</pre><p>In N26 we prefer to have a clear separation, so if we want to put the values in the store, we will always read them from the <strong>Get</strong>’s infinite stream. In the other side, the <strong>Fetch</strong> will feed the store and never return the fetched value. We use the <strong>Request</strong> to get the values once from a Single, but this method will never feed the store. Summarising, we don’t have a method that returns the values once through a Single and feeds the store at the same time, even though technically is possible.</p><p><strong>Get</strong>, <strong>Fetch</strong> and <strong>Request</strong> are not the only operations in the Repository, we sometimes also need to send something to our external source (API):</p><pre>Single&lt;CreditDraft&gt; deleteCreditDraft(CreditDraft draft) {<br>    return creditService.deleteCreditDraft(draft)<br>                        .subscribeOn(Schedulers.<em>io</em>())<br>                        .observeOn(Schedulers.<em>computation</em>())<br>                        .map(creditDraftMapper);<br>}<br><br>Single&lt;CreditDraft&gt; pushCreditDraft(CreditDraft draft) {<br>    return creditService.putCreditDraft(draft)<br>                        .subscribeOn(Schedulers.<em>io</em>())<br>                        .observeOn(Schedulers.<em>computation</em>())<br>                        .map(creditDraftMapper);<br>}</pre><h3>Domain</h3><p>At this point our data layer is ready, we have a Repository that we can inject in the domain layer.</p><p>For this specific example we need a RetrieveInteractor, we are going to call it RetrieveCreditDraftList. In this case there are no inputs required to perform this operation and the out put is List&lt;CreditDraft&gt;, which results in RetrieveInteractor&lt;Void, List&lt;CreditDraft&gt;&gt;. This type of interactor has to implement the getBehaviorStream() method that should return a Flowable:</p><pre>Flowable&lt;List&lt;CreditDraft&gt;&gt; getBehaviorStream(Option&lt;Void&gt; params) {<br>    return creditRepository<br>            .getAllCreditDrafts()<br>            // fetch if emitted value is none<br>            .flatMapSingle(this::fetchWhenNoneAndThenDrafts)<br>            // unwrap if some, filter if none<br>            .compose(UnwrapOptionTransformer.<em>create</em>());<br>}<br><br>private Single&lt;...&gt; fetchWhenNoneAndThenDrafts(Option&lt;...&gt; drafts) {<br>    return fetchWhenNone(drafts).andThen(<em>just</em>(drafts));<br>}<br><br>private Completable fetchWhenNone(Option&lt;...&gt; drafts) {<br>    return drafts.isNone()<br>            ? creditRepository.fetchCreditDrafts()<br>            : Completable.<em>complete</em>();<br>}</pre><p>The chain starts with the infinite Flowable that comes from creditRepository.getAllCreditDrafts(). This stream is designed to never end, complete or error. It also emits right after subscription the stored value or NONE if the store is empty. Is this interactor’s responsibility to perform the necessary actions to retrieve the List&lt;CreditDraft&gt; from all the available sources, internal (store) or external (API). To achieve this, it checks the emitted elements by the repository’s Flowable, if the value isNONE means that the store is empty and it is required a fetch operation. The last step in the chain is to unwrap the Option in the case there is some value inside or filter it out when is NONE.</p><p>It is important to note that the chain is built in such a way that if there is an error coming from the fetch operation it will be forwarded, so the resulting Flowable&lt;List&lt;CreditDraft&gt;&gt; from the interactor is designed to error. This way the presentation layer can decide to show some sort of visual feedback in such a case. Also, the interactor is filtering out the case when the store is empty, this means the Flowable from the interactor won’t emit anything in such case. The idea is that the presentation layer doesn’t care about this type of details, it just cares about getting the List&lt;CreditDraft&gt; when is ready. The interactor will make this happen and will abstract the process for the presentation layer or any other consumer.</p><p>The RetrieveCreditDraftList would be enough already for the feature we are working on in this post, but for the sake of having more examples let’s imagine it is required that the CreditDraft objects in the list must be ordered. The interactor we just created is a first level interactor, it coordinates the base operation of retrieving the List&lt;CreditDraft&gt;, now this one can serve to many other second level interactors that can build on top and perform some further transformations. For instance, we could have a RetrieveOrderedCreditDraftList interactor:</p><pre>Flowable&lt;List&lt;CreditDraft&gt;&gt; getBehaviorStream( Option&lt;OrderingStrategy&gt; params) {<br>    OrderingStrategy strategy = unwrapOrThrow(params);<br>    return retrieveCreditDraftList<br>            .getBehaviorStream(Option.<em>none</em>())<br>            .map(drafts -&gt; orderDrafts(drafts, strategy));<br>}</pre><p>Let’s go through another example. Let’s say it is required to delete a CreditDraft and we have to create an interactor for it. We would then create a DeleteInteractor&lt;DeleteCreditDraftParams, CreditDraft&gt; that would look like this:</p><pre>Single&lt;CreditDraft&gt; getSingle(Option&lt;DeleteCreditDraftParams&gt; params) {<br>    DeleteCreditDraftParams deleteParams = unwrapOrThrow(params);<br>    return creditRepository<br>            .deleteCreditDraft(deleteParams.creditDraftId())<br>            .flatMapSingle(this::fetchAndThenDraft);<br>}<br><br>@NonNull<br>private Single&lt;CreditDraft&gt; fetchAndThenDraft(CreditDraft draft) {<br>    return creditRepository.fetchCreditDrafts()<br>                           .andThen(<em>just</em>(draft));<br>}</pre><p>Deleting the CreditDraft with the passed id is not the only thing this interactor does, it also triggers a fetch after a successful delete operation. We expect changes in the List&lt;CreditDraft&gt; in the external source after a delete operation and therefore we want to update the ReactiveStore accordingly. The consumers of the RetrieveInteractor don’t know anything about other parts in the app where a DeleteInteractor has been triggered, but still they’ll get the new set of data once the ReactiveStore has been updated.</p><h3>Presentation</h3><p>We are almost done with our feature, the last step is to take the List&lt;CreditDraft&gt; coming from the RetrieveCreditDraftList interactor and transform it to the view entities.</p><p><strong>1. Design the view entities</strong></p><p>The view entities must be as easy as possible for the views to consume so they should be designed with the view in mind. For simplicity, we are only going to take care of CreditDraft objects that are in the in repayment state, so we only need one view entity: the InRepaymentCardViewEntity. In a real world case we would need to define more view entities for the different states a CreditDraft can be in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpDkpCDddMslw30dh14Avg.png" /><figcaption>View entity and the view it represents</figcaption></figure><p><strong>2. First level mappers: Map the domain objects to view entities</strong></p><p>Next step is to create a mapper that transforms the objects coming from the interactors in the domain layer into view entities. This operation is done in mappers, more precisely for this example:</p><pre>class InRepaymentCardViewEntityMapper implements Function&lt;CreditDraft, InRepaymentCardViewEntity&gt; {<br><br>    @NonNull<br>    public InRepaymentCardViewEntity apply(CreditDraft draft) {<br>        ...<br>    }<br>}</pre><p>The mappers can take other dependencies, like providers or utilities, if they are needed to perform the mapping to the final view entity.</p><p><strong>3. Second level mappers: Apply common mappings to view entities</strong></p><p>For a good design in our code each class should do one thing and one thing only, this is why sometimes higher level mappers are required. Usually this mappers perform some common combinations or transformations to the first level mapper’s output.</p><p>Now, to understand why we need a second level mapper here we need to briefly explain how our list is going to work. The goal is to display the view entities in a RecyclerView. We have a RecyclerAdapter with a method to update the items that looks like this: update(List&lt;DisplayableItem&gt;). The DisplayableItem is just a wrapper to abstract the actual type of the view entities and be able to show different elements in the same RecyclerView. How this exactly works is out of the scope of this post but the code can be found in the <a href="https://github.com/n26/N26AndroidSamples">repository</a>.</p><p>With this in mind, there is a final transformation we need to apply to every view entity:</p><pre>class CreditDisplayableItemMapper implements Function&lt;List&lt;CreditDraft&gt;, List&lt;DisplayableItem&gt;&gt; {<br><br>    List&lt;DisplayableItem&gt; apply(List&lt;CreditDraft&gt; creditDrafts) {<br>        return Observable.<em>fromIterable</em>(creditDrafts)<br>                         .map(inRepaymentCardViewEntityMapper)<br>                         .map(this::wrapInDisplayableItem)<br>                         .toList()<br>                         .blockingGet();<br>    }<br>}</pre><p>In this case the transformation is very simple because we are only taking care of the InRepaymentCardViewEntity. In the case we would have other view entities, the CreditDisplayableItemMapper would be constructed with all the first level mappers and it would coordinate the process of wrapping each view entity inside the DisplayableItem.</p><p><strong>4. Put the pieces together in the </strong><strong>ViewModel</strong></p><p>We now have to create the CreditDashboardViewModel and connect everything together. The ViewModel is going to bind to the domain layer and update the LiveData every time there is an emission. This subscription happens when the ViewModel is created:</p><pre>CreditDashboardViewModel(RetrieveCreditDraftList interactor,<br>                         CreditDisplayableItemMapper mapper) {<br>    this.retrieveCreditDraftList = interactor;<br>    this.creditDisplayableItemMapper = mapper;<br>    // Bind view model<br>    compositeDisposable.add(bindToCreditDrafts());<br>}</pre><p>The resulting disposable from the subscription must be stored and disposed when the ViewModel <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html">is cleared</a>. This happens in the onCleared method that we need to override:</p><pre>@Override<br>protected void onCleared() {<br>    super.onCleared();<br>    compositeDisposable.dispose();<br>}</pre><p>Let’s now see how the binding of the ViewModel to the interactor happens. The starting point is the Flowable that is exposed in the RetrieveCreditDraftList interactor, this Flowable can emit onNext or onError events. When there is a successful update of the data, it will emit onNext and the emitted List&lt;CreditDraft&gt; will be transformed into List&lt;DisplayableItem&gt; thanks to the CreditDisplayableItemMapper that we just created. Finally, this List&lt;DisplayableItem&gt; will be passed to the LiveData object. This chain will keep working as long as there are no errors coming through.</p><pre>private Disposable bindToCreditDrafts() {<br>    return retrieveCreditDraftList<br>            .getBehaviorStream(<em>none</em>())<br>            .map(creditDisplayableItemMapper)<br>            .subscribe(creditListLiveData::postValue,<br>                       this::handleError<br>}</pre><blockquote>What happens when there is an error coming from RetrieveCreditDraftList?</blockquote><p>The RetrieveCreditDraftList interactor is designed to error. As we saw before, a fetch operation is performed when the repository doesn’t provide the requested values. This fetch operation can fail and we need to propagate this error to the presentation layer so we can decide what to do. There are two things to consider in this scenario:</p><ul><li>Do we want to show something in the view to give feedback about the error? If this is the case, we should then create a ErrorViewEntity POJO which will describe the <em>error view </em>as close as possible<em>. </em>In the same way we update the LiveData with the list of credits when there is an onNext event, we should then update a LiveData object with the ErrorViewEntity when there is an onError event.</li><li>Do we want to retry? After the onError event the subscription is over, the chain will stop to work and we will not receive further updates. There are operators like retry(), retryUntil() or retryWhen() that can help us to recover from this state. What they do is to resubscribe to the source in case of error following a strategy that we can specify.</li></ul><p><strong>5. Hook the view to the </strong><strong>LiveData</strong></p><p>The final step is to setup the view to consume the LiveData provided by the ViewModel. In this case we have the CreditDashboardFragment which only consumes the LiveData&lt;List&lt;DisplayableItem&gt;&gt;:</p><pre>@Override<br>public void onActivityCreated(Bundle savedInstanceState) {<br>    super.onActivityCreated(savedInstanceState);<br>    viewModel.getDisplayableItemListLiveData()<br>             .observe(this, adapter::update);<br>}</pre><p>To know more about LiveData and ViewModel check out the official <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a> page.</p><p>This is the end of our journey, the feature is ready! Assuming we wrote unit tests as we made the different implementations, of course ;)</p><p>Check out the sample repository if you are interested on seeing how everything fits together in more detail:</p><p><a href="https://github.com/n26/N26AndroidSamples">n26/N26AndroidSamples</a></p><p><strong>Interested in joining one of our teams as we grow?</strong></p><p>If you’d like to join us on the journey of building the mobile bank the world loves to use, have a look at some of the Tech roles <a href="https://n26.com/en/careers/departments/13426?gh_src=3824fb5e1&amp;utm_source=magazine&amp;utm_medium=article&amp;utm_content=practical-example-using-reactive-clean-architecture-approach">we’re looking for here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2436ea76b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insiden26/practical-example-using-reactive-clean-architecture-approach-8a2436ea76b4">Practical example using Reactive Clean Architecture approach</a> was originally published in <a href="https://medium.com/insiden26">InsideN26</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Clean Architecture with Android Architecture Components]]></title>
            <link>https://medium.com/insiden26/reactive-clean-architecture-with-android-architecture-components-685a6682e0ca?source=rss-d866ff513d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/685a6682e0ca</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Lucia Payo]]></dc:creator>
            <pubDate>Tue, 05 Sep 2017 12:13:32 GMT</pubDate>
            <atom:updated>2018-10-31T09:52:42.700Z</atom:updated>
            <content:encoded><![CDATA[<p>What happens if we take reactive, clean architecture and the recently released android architecture components and put all of them together? This is what we did in <a href="https://play.google.com/store/apps/details?id=de.number26.android">N26</a> and the result is working pretty well:</p><ul><li>There is a clean separation of concerns, making the features easier to navigate in code.</li><li>Brings a common understanding on how to build features, which makes it easier to review each others’ code.</li><li>As we apply this architecture, we create more content that can be reused and development becomes faster.</li><li>Reactive programming brings a higher level of abstraction to the way we code, removing some of the weight from our side.</li></ul><p>In this initial post we are going to explain the main ideas behind the architecture and how it works, it is going to be more theoretical than practical, that’s why we’ve decided to create a second post explaining step by step how to apply this architecture in a practical case:</p><p><a href="https://mag.n26.com/practical-example-using-reactive-clean-architecture-approach-8a2436ea76b4">Practical example using Reactive Clean Architecture approach</a></p><p>We have also created a small app to showcase the architecture that can be found in this repository:</p><p><a href="https://github.com/n26/N26AndroidSamples">n26/N26AndroidSamples</a></p><h4>What do we exactly mean by reactive?</h4><p>We realised there are several ways to use RxJava. The most straightforward one is for asynchronous calls, where you subscribe to an Observable that will eventually emit onNext or onError and complete afterwards, a typical example of this are the observables from retrofit calls. It’s like a callback on steroids, you can control the threads where things are executed very easily and there’s a bunch of very powerful operators that allow you to combine/transform the result. This is a great way to use RxJava but there’s more.</p><p>In most apps there’s a set of data that is the core information of the app, on which the features are based. For instance, in N26 we have different tabs in the main screen that show credit, insurances, all the movements in the account, etc. All these views show the user’s info that we get from the backend. This data is the heart of the app and everything is based on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*BZkVtVxDIMPOBHQul2kP9w.png" /><figcaption>N26 insurance feature</figcaption></figure><blockquote>What if we could observe this data forever and receive a new version of it every time it changes?</blockquote><p>The difference with the previous scenario is that the streams never end, so it is possible to subscribe to them once and keep receiving updates of the observed data until the consumer decides to unsubscribe. In other words, the producer is not in charge of deciding when the stream ends, the consumer will decide when it should stop receiving events by unsubscribing. This is what we mean by reactive and the core idea behind the architecture presented in this series.</p><h3>Reactive clean architecture</h3><p>Most of developers are familiar with clean architecture and it helps a lot when it comes to separation of concerns in the app. We followed its guidelines to separate our features in three layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCtjibLEvgIpmWBjYzHvXQ.png" /><figcaption>Clean Architecture layers</figcaption></figure><h4><strong>Data</strong></h4><p>The responsibility of this layer is to manipulate and coordinate the different sources of data. It has three main components: the repository, the network services and the reactive store .</p><p>The main idea is to get the data from the external source through the network services, store this data inside the reactive store, which can be seen as the internal data source, and expose the data through the repository to the upper layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_kLTDyq_j-dZgprOcSqJQ.png" /><figcaption>Main components of the data layer</figcaption></figure><p><strong>The repository</strong></p><p>It is the access point and the interface to the outside. These are the four main operations that are exposed in this layer:</p><ul><li><strong>Get:</strong> Returns an infinite stream that will emit updates of the specified type of data but doesn’t ensure there will be a value inside. The stream is built so it emits right after subscription and emits NONE when the store is empty. This stream is designed to not complete or error.</li><li><strong>Fetch:</strong> It fetches the data from external sources, typically from API, and stores the data once it receives it. This is the action that feeds the “Get”. Returns a Completable that signals whether the fetch has completed or error. Note that there is no onNext<em> </em>event in Completable<em>, </em>this means the fetched data will not return in any way through the fetch method.</li><li><strong>Request: </strong>This is an alternative to fetch operation when we don’t need the infinite stream counterpart. It returns a Single that will return the data in the onNext event and complete or error if there was any problem.</li><li><strong>Push, Delete:</strong> It sends or deletes data to and from external sources. Provides a Single<em> </em>or a Completable<em> </em>depending if there is any data coming back from this operations.</li></ul><p><strong>The reactive store</strong></p><p>This is the component behind the <strong>Get</strong>. It holds the data and provides infinite streams to it. Is the most complex part of the whole architecture and must be designed carefully: this layer will be holding the data and will be accessed asynchronously,<strong> it must be solid against concurrency</strong>.</p><p>There are many ways of implementing this component depending on the nature of the features in the app. For the architecture to work, this is how the interface should look like:</p><pre>public interface ReactiveStore&lt;Key, Value&gt; {</pre><pre>    Flowable&lt;Option&lt;Value&gt;&gt; getSingular(@NonNull final Key key);</pre><pre>    Flowable&lt;Option&lt;List&lt;Value&gt;&gt;&gt; getAll();</pre><pre>    void storeSingular(@NonNull final Value model);</pre><pre>    void storeAll(@NonNull final List&lt;Value&gt; modelList);<br>}</pre><ul><li>Provides two types of “get” methods: the getSingular(id), to get a stream that will emit updates of the singular element with the passed id, and the getAll(), to get a stream that will emit updates when there is changes in any of the elements inside the store.</li><li>Provides two types of “store” methods: the storeSingular(object)<em> </em>and the<em> </em>storeAll()<em>.</em></li><li>When storeSingular(object) is called, both the getSingular(id) and the getAll() should emit.</li><li>When storeAll() is called, getAll() and all the existing getSingular(id)<em> </em>should emit.</li><li>Both getAll() and getSingular(id) emit right after subscription.</li><li>Both getAll() and getSingular(id)<em> </em>emit NONE<em> </em>when the store is empty.</li></ul><p>The streams are created on request, this way we know when the data is being observed and only update the stream in this case.</p><p>Some other operations could be added, such as replaceAll()<em> </em>or clear()<em>, </em>as long as the streams are updated consistently.</p><p>Under these component we can coordinate the process of storing data in one or more forms of storage. The simplest would be having a memory cache but it could also be a database, the file system, shared preferences or anything else that could be considered a persistence method. It is also possible to have a combination one or more of these methods, for instance, the combination of memory cache on top of database. The possibilities are many, we just have to coordinate the process of storing the objects and feeding the streams accordingly.</p><p>We also want to share with you some of the solutions we came up in N26 for the reactive store. They’ll be coming up soon in different blog posts, stay tuned!</p><p><strong>Mapping before storing</strong></p><p>The plan is to put in the store the objects that are going to be consumed by the layers on top. This layer will build use cases out of these objects so let’s make sure the data we store is in good conditions.</p><p>Most of apps get the data from an API, which has a contract that describes what data and what format this API should serve the data. In 99% of the cases this contract is satisfied but… what happens when it is not? We could spend hours debugging, thinking there is a bug in the app’s code when the actual problem is a missing field in the API response.</p><blockquote>What if we design the entry point of the app to check a set of constraints or conditions and if they are not met show an error message describing exactly what is wrong?</blockquote><p>This can be achieved by defining two POJOs, one that represents the object that comes from the external source, we refer to this as the “raw” entity<em>, </em>and another one that is the mapped object, the one that has been checked and is safe to store, we call this one the “safe” entity. By mapping the raw entity to the safe entity before storing it we are creating a first line of defence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*332sana2z2jCixL3NNwNfw.png" /><figcaption>Raw to safe entity mapping</figcaption></figure><p>One of the things we do in N26 app is to get rid of the null in our code as much as we can, we use Options instead to represent the possibility of the absence of an object. More precisely we use the <a href="https://github.com/tomaszpolanski/Options">Options</a> library from <a href="https://medium.com/u/12240235795b">Tomek Polański</a>.</p><p>The perfect place to get rid of null is in this mapper, where every parameter can be checked and mapped toOption&lt;Parameter&gt; in the case is fine when is missing, or for the contrary, throw an exception if it is a mandatory parameter for the feature to operate.</p><h4>Domain</h4><p>This layer sits on top of the data and is responsible for coordinating the actions to the repository. It can also perform some mappings to prepare the objects coming from the data layer, that way the presentation layer can consume them easily. We call the main component in this layer the ReactiveInteractor<em>. </em>As you can see in the snippet below, we’ve defined several types to describe the nature of the different operations.</p><pre>interface SendInteractor&lt;Params, Result&gt; {<br><br>    Single&lt;Result&gt; getSingle(Option&lt;Params&gt; params);<br>}</pre><pre>interface DeleteInteractor&lt;Params, Result&gt; {</pre><pre>    Single&lt;Result&gt; getSingle(Option&lt;Params&gt; params);<br>}</pre><pre>interface RetrieveInteractor&lt;Params, Object&gt; {<br><br>    Flowable&lt;Object&gt; getBehaviorStream(Option&lt;Params&gt; params);<br>}<br><br>interface RefreshInteractor&lt;Params&gt; {<br><br>    Completable getSingle(Option&lt;Params&gt; params);<br>}</pre><pre>interface RequestInteractor&lt;Params, Result&gt; {<br><br>    Single&lt;Result&gt; getSingle(Option&lt;Params&gt; params);<br>}</pre><p>All of them define an Option&lt;Params&gt; as input. This way we can pass any input if needed, but also we can pass NONE in the case the specific operation doesn’t require anything.</p><p>They return different types of reactive objects depending on the nature of the operation:</p><ul><li>SendInteractor, DeleteInteractor and RequestInteractor, they all return a Single since the nature of all this operations is to provide a result and complete.</li><li>RetrieveInteractor returns a Flowable designed to never complete. This one can be seen as the domain version of the data layer’s <strong>Get</strong> operation, although there are some important differences. The data layer’s <strong>Get </strong>can be seen as a “pipe” to some form of storage. It doesn’t guarantee there’s going to be an actual value in the store, in which case it will notify this state by emitting NONE as we saw before. RetrieveInteractor is different since it has to guarantee the value. Meaning that it has to do whatever is possible to get this value or error in case it wasn’t possible. This usually means triggering a fetch if the Flowable from the data layer’s <strong>Get</strong> emits NONE.</li><li>RefreshInteractor is in charge of performing the necessary actions to update the data layer. This operation will cause the Flowable of the RetrieveInteractor to emit due to the nature of the data layer.</li></ul><p>The ReactiveInteractors can be combined and nested. It can be seen as different level of interactors. The lowest level interactor is the one that accesses the repository directly. A higher level interactor could use one or more of this lower level interactors and map the results. The idea is that each interactor does one thing and one thing only, this way is like having pieces that you can put together to build something bigger.</p><p>The domain is 100% Java only, meaning that there are no Android framework related objects here.</p><h4>Presentation</h4><p>This is the last layer, responsible for building the objects the views are going to consume and processing the actions performed in this views. This is also the layer where the <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a> are used, more specifically, the LiveData and the ViewModel.</p><p>The pattern for communicating with the views is MVVM. The idea is that the ViewModel provides the view with a LiveData&lt;ViewEntity&gt; object to consume. The view entity should be designed to represent as close as possible the state of one specific view. Some time ago I wrote a <a href="https://medium.com/upday-devs/mvvm-rxjava-learnings-1819423f9592">blog post</a> about how to design this view entities safely, things that need to be taken into account when dealing with RxJava + MVVM.</p><p>In MVVM pattern, the ViewModel is the component that interacts with the views, this leads to often have big view models, especially when the screen is complex. We tried to simplify our view models delegating some responsibilities to other components:</p><ul><li><strong>Mappers and transformers</strong>: They transform the objects coming from the domain layer to view entities.</li><li><strong>Providers</strong>: Sometimes we need something from the framework to build our view entity, for instance, we might need a specific string. We create the StringProvider to abstract the access to this resource.</li><li><strong>Utilities</strong>: There is not much to say here, these are the classical utility classes that contain helper functions.</li></ul><p>The View Model should not do any of the things the components above can do. <strong>The View Model should coordinate the process of creating view entities and put all the pieces together</strong>. After doing this we noticed several benefits: the most obvious one was that the view models have a much smaller size, everything was easier to test since each class has a more specific and narrow responsibility, it is more clear what are the inputs/outputs and what is expected from each class. Of course this also makes the whole presentation layer more understandable and readable.</p><p><strong>The importance of a well designed view entity</strong></p><p>One common mistake is to pass the view an object that hasn’t been designed for it, usually because we don’t want to create another object that is specific for the view, so we rather just pass the one that comes from our data or domain layer. This should be avoided because it means that the view needs to do some final transformations to be able to consume it, leaving code that contains untested logic.</p><p>In our experience, the most critical step working in the presentation layer is the design of the view entities. Creating these POJOs is in a way the main goal of the presentation layer and defines how readable, understandable and testable the whole layer is.</p><blockquote>Take your time designing the view entities. You don’t want to deal with a poorly designed one and it is painful to change them when the implementation of the presentation layer is advanced.</blockquote><h3>Asynchronous nature</h3><p>When dealing with this type of architecture it is important to have present the asynchronous nature of it. The architecture uses streams extensively, this means <strong>we are embracing asynchronous programming</strong>. RxJava allows us to do this in a very easy way, is very powerful, but great powers always come with great responsibilities.</p><p>The architecture is based on the idea of event based programming: you get events that you can combine, transform or do some other things through the streams, but the events are meant to be transient and immutable, they exist at one point in time inside a function in the chain, until they are transformed into some other object and passed down. So <strong>DON’T</strong>:</p><ul><li>Mutate the object in the event, always create a new one. This can be achieved by enforcing immutability in all the objects, which is a general good practice.</li><li>Store the object from the event in a local/global variable. This object’s scope is in the function and shouldn’t exist outside.</li></ul><p>The last point is aiming to eliminate all the unnecessary internal intermediate states we sometimes create thinking they’ll make our lives easier. For instance, a variable in the class to store the latest result of an operation that we want to compare with next time, or an internal flag to know if an operation has already been performed. When we create these type of states we are not in control, we are ignoring the asynchronous nature of our code, but ignoring it doesn’t make it disappear, we are setting up a trap for ourselves, this is the perfect scenario for corrupted states and race conditions. RxJava provides operator with memory so use them, they’ve been designed to work in a reactive asynchronous environment.</p><p>This is the end of this first post, if you are ready to see this architecture in action with a practical example check out the follow up post!</p><p><a href="https://mag.n26.com/practical-example-using-reactive-clean-architecture-approach-8a2436ea76b4">Practical example using Reactive Clean Architecture approach</a></p><p><strong>Interested in joining one of our teams as we grow?</strong></p><p>If you’d like to join us on the journey of building the mobile bank the world loves to use, have a look at some of the Tech roles <a href="https://n26.com/en/careers/departments/13426?gh_src=3824fb5e1&amp;utm_source=magazine&amp;utm_medium=article&amp;utm_content=reactive-clean-architecture-with-android-architecture-components">we’re looking for here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685a6682e0ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insiden26/reactive-clean-architecture-with-android-architecture-components-685a6682e0ca">Reactive Clean Architecture with Android Architecture Components</a> was originally published in <a href="https://medium.com/insiden26">InsideN26</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM + RxJava: Learnings]]></title>
            <link>https://medium.com/upday-devs/mvvm-rxjava-learnings-1819423f9592?source=rss-d866ff513d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/1819423f9592</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Lucia Payo]]></dc:creator>
            <pubDate>Tue, 08 Nov 2016 17:01:41 GMT</pubDate>
            <atom:updated>2017-09-16T11:08:28.573Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b#.41u9x3ds1">MVVM</a> + RxJava is a great formula for an app architecture. At upday we recognised this and used it in our app, making it scalable and maintainable. Despite this, we’ve had to learn a few lessons the hard way.</p><p>In this blog post, I’ll be sharing two of these learnings using the actual specific scenarios that inspired them. As a result, I’ll be drilling right down into the details of the code. Now, if you’re a little short on time, here are the two takeaways:</p><ol><li>Expose states instead of events.</li><li>Everything should go through the view model.</li></ol><p>If you’re ready to learn more about the <em>how and why</em>, let’s go!</p><h3>Expose states and not events</h3><p>The core feature of upday is to show news to the user in a way that is easy to read and fluid. With this specification the ViewPager seemed a good choice, we could present the news in form of cards one after the other. More specifically we need to implement the following behaviors:</p><ol><li>Scroll to a certain position.</li><li>Replace/update the elements in the ViewPager.</li><li>Replace/update the elements in the ViewPager AND scroll to a certain position.</li></ol><p>Reading those requirements it seems very natural to have an Rx stream with the position and a different Rx stream with the set of cards. All we need to do is to expose these two streams in the view model so the Fragment can subscribe to them and issue the received events to the adapter and/or ViewPager.</p><p>So this is the plan: do the processing of the position and the data set separately in background threads inside the view model, expose these streams and subscribe to them in the Fragment, switch to the main thread only to receive the events and modify the views. In theory this should work, we are separating business logic from framework related logic pretty well, we are making the Fragment very dumb so we can unit test most of the logic via the view model. We are also doing all the processing in background threads, only using the main thread when is necessary. What could go wrong?</p><pre>public class NewsFragment extends Fragment {</pre><pre>    private NewsViewModel mViewModel;<br>    private ViewPagerAdapter mAdapter;<br>    private ViewPager mViewPager;<br>    private final CompositeSubscription mSubscription = <br>        new CompositeSubscription();</pre><pre>    // Set up fragment (onCreate, etc.)</pre><pre>    @Override<br>    public void onResume() {<br>        super.onResume();<br>        mSubscription.add(subscribeToPositionChanges());<br>        mSubscription.add(subscribeToCardChanges());<br>    }</pre><pre>    private Subscription subscribeToPositionChanges() {<br>        return mViewModel.getPositionStream()<br>                         .observeOn(AndroidSchedulers.mainThread())<br>                         .subscribe(mViewPager::setCurrentItem,<br>                                    this::handleError);<br>    }</pre><pre>    private Subscription subscribeToCardChanges() {<br>        return mViewModel.getSetOfCardsStream()<br>                         .observeOn(AndroidSchedulers.mainThread())<br>                         .subscribe(mAdapter::update,<br>                                    this::handleError);<br>    }</pre><pre>    @Override<br>    public void onPause() {<br>        mSubscription.clear();<br>        super.onPause();<br>    }<br>}</pre><p>We did exactly this and started receiving bug reports indicating a wrong end state in the ViewPager. Those types of bugs usually have the feared characteristic of not being 100% reproducible. We had to face the brutal reality: we had race conditions, but why? We have a neat architecture using MVVM, everything is unit tested and we use RxJava to send events.</p><p>The best way to explain what was happening is with an example. So imagine that we initially have a data set with 5 items in the ViewPager and the actual position is 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Kn4lGcsXW1LDHIIGggpN1w.png" /></figure><p>Now, the user performs an action and the final expected state is to have 9 elements in the ViewPager centered at position 7. All the RxJava events trigger after the user action, <strong>we don’t have any control over when things happen</strong>, naïvely, we just sit there and hope that everything is setup correctly and, somehow, it comes together in the end. But it doesn’t. Actually in some cases the position stream emits a 7 before the data set stream emits the 9 elements. The position event is captured by the fragment that tells the ViewPager to move to the position 7 but it only has 5 elements, how can it move to position 7? It can’t, so it simply ignores the command. It does not fail, it doesn’t let you know in any way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*4a2qIfYhyhHCo2jjP9LhmQ.png" /></figure><p>Right after this the data set event comes, but it is too late already, even though the adapter is going to replace the data set the ViewPager is not going to be centered in the right position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lm5Z088D1FpjH2C2JA-zjw.png" /></figure><p>Of course, this isn’t always the case, sometimes the data set event will come first and everything will work as expected. This is due to the asynchronous nature of our architecture. The view model is doing the processing of the data in background threads so when the user action comes, the position and the data set will be processed with no guarantee of which will finish first.</p><p>After all it wasn’t such a great idea to expose two parallel streams with events. What should we do then? The answer is simple, <strong>expose one stream per view that emits states instead of events</strong>. Both the position and the data set should be wrapped up together so the ViewPager never receives one without the other. This is true for any view with intra-dependent state. You would never expose two separate streams for a TextView, one that sets the text and another one that emits the position of the letter that should be highlighted in bold, but for some reason it’s much easier to make this mistake with a ViewPager or lists.</p><h3>Everything goes through the view model</h3><p>Sometimes upday receives breaking news in the form of push notifications so the user can know immediately that something important happened in the world. The expected behavior when the user taps on the notification is to open upday and show the card for the breaking news. Practically this means to open the top news Fragment and center its ViewPager in the position of the breaking news. Typically this type of news is placed in the first position, so for simplicity’s sake let’s assume all we need to do is to set the position of the ViewPager to zero.</p><p>We have a mechanism to capture the actions of the user in the push notifications that transforms them into a Rx stream so, why not subscribe to it directly in the Fragment? The operation here is trivial: when the stream emits an event the ViewPager should just scroll to position 0, there is no logic or transformation in-between that needs to be unit tested.</p><pre>breakingNewsStream().observeOn(AndroidSchedulers.mainThread())<br>                    .subscribe(event -&gt; ViewPager.setCurrentItem(0),<br>                               this::handleError);</pre><p>First of all, this is already breaking the previous rule of states instead of events since it is setting the position only, but even though we had a stream of ViewPager’s states it would still be wrong. The reason is that the view model is not aware of what just happened and we could have other things relying on what the view model says the current state is. So the next natural step here would be to notify the view model about what just happened.</p><pre>breakingNewsStream().observeOn(AndroidSchedulers.mainThread())<br>                    .subscribe(event -&gt; {<br>                                mViewPager.setCurrentItem(0);              <br>                                mViewModel.notifyCurrentPosition(0);<br>                               },<br>                               this::handleError);</pre><p>At this point we could think we did a great job, we solved the issue. The view model now knows what is going on and we can handle this state change properly. But again the reality is quite different and by doing this we have just shot ourselves in the foot. If we ever were to add other effects based on what the view model thinks the ViewPager’s state is, then we have again created a race condition. There is a window of time where the view model has been “notified” but the state has not yet been processed due to the asynchronous nature of the events.</p><p>The problem here is that we haven’t followed the natural pattern of our MVVM architecture. The view model transforms the data into something that is easy to use in the Views or any other consumer, this means <strong>the view should know about the changes always after the view model.</strong> In this example the View knows about the changes before the view model, making the later unreliable.</p><p>So basically, it doesn’t matter how trivial or easy an operation is, <strong>everything should go through the view model,</strong> this way other stuff that is based on the view model’s state can happen reliably.</p><p>For more details on how we implemented the Model-View-ViewModel pattern, check out one of our previous articles.</p><p><a href="https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b">Android Architecture Patterns Part 3:
Model-View-ViewModel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1819423f9592" width="1" height="1" alt=""><hr><p><a href="https://medium.com/upday-devs/mvvm-rxjava-learnings-1819423f9592">MVVM + RxJava: Learnings</a> was originally published in <a href="https://medium.com/upday-devs">upday devs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>