<?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 Alex Hart on Medium]]></title>
        <description><![CDATA[Stories by Alex Hart on Medium]]></description>
        <link>https://medium.com/@Exallium?source=rss-c9aafad647d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I0KtUteCaDl7EoLiEXkWXg.jpeg</url>
            <title>Stories by Alex Hart on Medium</title>
            <link>https://medium.com/@Exallium?source=rss-c9aafad647d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:21:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Exallium/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[Eager vs. Lazy in RxJava]]></title>
            <link>https://proandroiddev.com/eager-vs-lazy-in-rxjava-cf077b4757ba?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf077b4757ba</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[lazy-evaluation]]></category>
            <category><![CDATA[eager-execution]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 08:01:01 GMT</pubDate>
            <atom:updated>2019-08-01T08:01:01.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*3J7LZOt7bikPpSRGQUsFaA.jpeg" /><figcaption>An Eager Beaver. <a href="https://upload.wikimedia.org/wikipedia/commons/6/6b/American_Beaver.jpg">https://upload.wikimedia.org/wikipedia/commons/6/6b/American_Beaver.jpg</a></figcaption></figure><p>Over the last several years, RxJava has been a staple of Android software development. RxJava has a very high learning curve, and part of that is because you are really learning two different things at once. The first is the application of operators to a stream of values. This includes doing the normal routine tasks in RxJava that most people are used to.</p><pre>Observable.just(1, 2, 3, 4, 5)<br>    .map { it + 5 }<br>    .subscribe(::println)</pre><pre>// Prints 6, 7, 8, 9, 10</pre><p>The other half of the RxJava equation is that of the asynchronous threading model. Herein lies the need to understand the difference between eager and lazy evaluation, and to know a bit about how RxJava operates under the hood. In this post, I would like to build up an example of eager vs. lazy evaluation, and show why we might want to double check how RxJava works in different circumstances.</p><h3>Definitions</h3><p>First, it is best to define some terms. <a href="https://en.wikipedia.org/wiki/Eager_evaluation">Eager evaluation</a> means that when you assign an expression to a variable, the expression is evaluated immediately and the variable’s value is set. This leads to very straightforward, deterministic behavior in the software we write. This is the default in most programming languages such as Java, Kotlin, or C. On the other hand, <a href="https://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a> only evaluates at the last possible moment before the value is needed. If you never access the value, the code determining the value is never run. This is the default in languages like Haskell, and many other functional programming languages. With respect to RxJava, it is sufficient to say that eager operators try to do things as soon as possible, while lazy operators tend to wait until the very last moment.</p><h3>Minimizing Requests</h3><p>Let’s imagine a situation where we have multiple requests to a network service. While we are processing that request, we want to ignore any new requests. Such cases could be seen in the downloading of a configuration feed, uploading of some sort of data, etc.</p><p>Our first intuition might be to utilize a debounce . However, a debounce will wait the full length of the given timeout before emitting any data. After this timeout, it will emit the most recent item it received. This is the opposite of what we want, as we would prefer our network request to start as soon as possible.</p><p>One approach to solving this problem is to utilize a Flowable and an appropriate backpressure strategy. We can “fake” 5 button presses spaced 10ms apart utilizing an interval followed up with a take. We also add a strategy for our backpressure, via onBackpressureDrop.</p><p>Backpressure occurs when the downstream (stuff below the call to onBackpressureDrop) can not process the values being emitted from the upstream (stuff above the call to onBackpressureDrop) fast enough. In our case, we specified that they should be dropped. We could also Buffer, throw an error, or something else, as defined by the BackpressureStrategy enum.</p><pre>Flowable.interval(10, TimeUnit.MILLISECONDS)<br>    .take(5)<br>    .onBackpressureDrop()</pre><p>Now, let’s imagine we have some long-running task we want to perform on each emission. Because we are performing network IO, we’ll be sure to do this work on the IO threadpool.</p><pre><strong>fun </strong>webRequest(i: Long) = Single.create&lt;Long&gt; <strong>{<br>    </strong><em>println</em>(&quot;Preparing <strong>$</strong>i&quot;)<br>    Thread.sleep(100)<br>    <strong>it</strong>.onSuccess(i)<br><strong>}</strong>.subscribeOn(Schedulers.io())</pre><p>We can bring this into our stream like so:</p><pre>Flowable.interval(10, TimeUnit.MILLISECONDS)<br>    .take(5)<br>    .onBackpressureDrop()<br>    .flatMapSingle(::webRequest)<br>    .subscribe { println(&quot;Got $it&quot;) }</pre><p>Great! We can subscribe and away we go…</p><pre>Preparing 2<br>Preparing 3<br>Preparing 0<br>Preparing 1<br>Preparing 4<br>Got 4<br>Got 2<br>Got 3<br>Got 0<br>Got 1</pre><p>Whoops! Something’s wrong. Everything is out of order, and we processed everything, instead of dropping things one at a time. Well for one, we never actually told our stream that we only want to process a single value at a time. We can try to utilize a ResourceSubscriber to do this, invoking its request method. We’ll change our subscribe call to look like this:</p><pre>.subscribe(<strong>object </strong>: <em>ResourceSubscriber</em>&lt;Long&gt;() {<br><br>    <strong>override fun </strong>onStart() {<br>        <em>println</em>(&quot;Start&quot;)<br>        request(1)<br>    }<br><br>    <strong>override fun </strong>onComplete() {<br>        <em>println</em>(&quot;Completed&quot;)<br>    }<br><br>    <strong>override fun </strong>onNext(t: Long?) {<br>        <em>println</em>(&quot;Got <strong>$</strong>t&quot;)<br>        request(1)<br>    }<br><br>    <strong>override fun </strong>onError(t: Throwable?) {<br>        <em>error</em>(&quot;This should never happen&quot;)<br>    }<br>})</pre><p>Ok, so now we run again…</p><pre>Start<br>Preparing 0<br>Preparing 1<br>Preparing 2<br>Preparing 3<br>Preparing 4<br>Got 1<br>Got 0<br>Got 2<br>Got 4<br>Got 3<br>Completed</pre><p>Oh no. Our output looks the exact same. So what is happening? Notice how all of the Preparing calls are at the top of our output. This means that we’re calling each Preparing statement before <em>any</em> of our output is actually processed by our onNext override in our ResourceSubscriber. That’s a problem, because that would imply that every time the user hits our fabricated button, we are making a network request.</p><p>There is a handy method called doOnRequest that will help show us why we’re getting more data than expected. By inserting calls to doOnRequest to either side of our flatMapSingle, we can get some insight as to what is going on.</p><pre>.doOnRequest <strong>{ </strong><em>println</em>(&quot;A: <strong>$it</strong>&quot;) <strong>}<br></strong>.flatMapSingle(::webRequest)<br>.doOnRequest <strong>{ </strong><em>println</em>(&quot;B: <strong>$it</strong>&quot;) <strong>}</strong></pre><p>Our output looks like so:</p><pre>Start<br>B: 1<br>A: 9223372036854775807<br>Preparing 2<br>Preparing 0<br>Preparing 1<br>Preparing 3<br>Preparing 4<br>Got 2<br>B: 1<br>Got 0<br>B: 1<br>Got 1<br>B: 1<br>Got 3<br>B: 1<br>Got 4<br>B: 1<br>Completed</pre><p>Ok, that is a large number. It turns out that flatMapSingle is very eager to get some work done. It is important to remember that every operator in RxJava creates an internal subscription. In the case of Flowables, this subscription includes making a call to request to get some data from the upstream. By default, flatMapSingle just asks for as much data as possible. To restrict this, we can utilize an override to flatMapSingle .</p><pre>.flatMapSingle(::webRequest, <strong>false</strong>, 1)</pre><p>Here we are telling flatMapSingle that we only want 1 object at a time (our maxConcurrency value). We end up with the following output:</p><pre>Start<br>B: 1<br>A: 1<br>Preparing 0<br>Got 0<br>B: 1<br>Completed</pre><p>Which looks a lot better, and is what we really wanted in the first place. In fact, we can simplify our example. Originally, we were trying to restrict our data load with a ResourceSubscriber. This is not necessary. Because we have told our flatMapSingle to only accept one item at a time, we can eliminate this subscriber and utilize a simpler subscribe call.</p><pre>Flowable.interval(10, TimeUnit.MILLISECONDS)<br>    .take(5)<br>    .onBackpressureDrop()<br>    .flatMapSingle(::webRequest, <strong>false</strong>, 1)<br>    .subscribe <strong>{ </strong><em>println</em>(&quot;Got <strong>$</strong>it&quot;) <strong>}</strong></pre><p>There are similar overrides for other flatMap methods which you can utilize to get similar behaviors. The takeaway here is that you should look for opportunities to restrict the flow of data and decide on a backpressure strategy as early as possible. It will lead to less processing in the long run.</p><h3>Kotlin: {} vs. ()</h3><p>Another point of contention that comes up a lot with RxJava is the hours wasted to the difference between {} and () when invoking operators. This next example hopes to shed some light on the difference.</p><p>Consider the function createCompletable, which creates a Completable that simply prints off a given label, goes to sleep for 100ms, and then completes.</p><pre><strong>fun </strong>createCompletable(label: String) =<br>    Completable.create <strong>{<br>        </strong><em>println</em>(&quot;Created Completable <strong>$</strong>label&quot;)<br>        Thread.sleep(100)<br>        <strong>it</strong>.onComplete()<br>    <strong>}</strong></pre><p>We can construct a chain of Completable objects utilizing andThen. One possible valid implementation looks like so:</p><pre>createCompletable(&quot;A&quot;)<br>    .andThen <strong>{ </strong>createCompletable(&quot;B&quot;) <strong>}<br>    </strong>.subscribe()</pre><p>However, when we run this, all we see is:</p><pre>Created Completable A</pre><p>What happened to B? Well, we used {} instead of (). In Kotlin, there is syntactic sugar that lets you move lambdas outside of a method’s () provided they are the last argument. Where this confusion comes in is that andThen utilizes a SAM interface, CompletableSource. This interface has a single method, with the signature (CompletableObserver) -&gt; Unit. There is nothing returned from this method, so calling arbitrary statements within it have no effect.</p><p>In our example, we are calling createCompletable(&quot;B&quot;). However, this is never executed, because it is never subscribed to. RxJava is lazy by default. Creating a Completable, Single, Maybe, etc. only creates the method by which to process a stream, but does not begin execution. The stream is not created and the operators are not invoked until such time as some interested party subscribes. We can fix our case in one of two ways. The first is to utilize the input argument.</p><pre>createCompletable(&quot;A&quot;)<br>    .andThen <strong>{ </strong>createCompletable(&quot;B&quot;).subscribe(it) <strong>}<br>    </strong>.subscribe()</pre><p>The second is to utilize () instead of {} since a Completable is a CompletableSource .</p><pre>createCompletable(&quot;A&quot;)<br>    .andThen(createCompletable(&quot;B&quot;))<br>    .subscribe()</pre><p>In both cases the Completable returned by createCompletable(&quot;B&quot;) is properly subscribed to and run. This results in the expected output:</p><pre>Created Completable A<br>Created Completable B</pre><h3>Conclusions</h3><p>RxJava is a massive, complex library. It is trying to do a lot of different things, and sometimes its helpful nature can hinder you in unexpected ways. Being able to separate creation from execution, and understanding the tools necessary to determine when RxJava is not being as lazy as you would like are key to a happy, successful experience. I hope that this post was able to explain away some of the ambiguity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf077b4757ba" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/eager-vs-lazy-in-rxjava-cf077b4757ba">Eager vs. Lazy in RxJava</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract / Extract / Inject]]></title>
            <link>https://medium.com/well-red/abstract-extract-inject-c5583bc79f83?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5583bc79f83</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 12:02:27 GMT</pubDate>
            <atom:updated>2018-10-10T12:02:27.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Armfkj174Qo8nhhLkl59cw.jpeg" /><figcaption><a href="https://images.pexels.com/photos/1181345/pexels-photo-1181345.jpeg">https://images.pexels.com/photos/1181345/pexels-photo-1181345.jpeg</a></figcaption></figure><p>Legacy code is a part of life for any software developer. There are many definitions of ‘Legacy Code’. Some consider it to simply be any code you’ve written. Some consider it code that has actually been released. Whatever that definition may be, we need to be able to deal with it, be it fixing bugs or building out new features.</p><p>In this post, we’ll work through an approach for the introduction of new features into a legacy code base. This approach is not a new one; it’s well documented and discussed in such books as <em>Refactoring</em> by Martin Fowler, as well as <em>Working Effectively with Legacy Code</em>, by Michael C. Feather. The strategy presented here will work just as well in any modern industrial programming language; be it Java, Typescript, etc. It leverages S.O.L.I.D. design principles, a few design patterns, and benefits greatly from the use of Continuous Integration and Feature Flags.</p><p>The original post that I wrote about this feature was in Kotlin and targeted at Android developers. Here I’ve reworked the examples to direct the content of this article towards web developers. Thus all examples in this work are in Javascript and utilize CommonJS modules. If you are interested in reading the original version, it can be found at the end of this article.</p><h3>Setup</h3><p>Let’s assume that we have a legacy application and that the application in question has analytics code strewn through it. A snapshot of our business logic could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb139128c7412ec3f3eed792a22849d/href">https://medium.com/media/fcb139128c7412ec3f3eed792a22849d/href</a></iframe><p>Here, we have a third party library called ExternalAnalytics, and we are importing it directly into a module which contains our business logic. Unfortunately, in a quarterly planning meeting, the Analytics team mentioned that they planned to deprecate ExternalAnalytics in a few months. There are many solutions to this problem, but I believe applying Abstract / Extract / Inject is one of the better approaches for something like this.</p><h3>Abstract</h3><p>In our prior example, our business logic is dependent on a third party library directly. This is problematic because changes to third-party dependencies should not require us to change our business logic. Since the Analytics team wants us to be able to swap out our library, we need a way to express what actions we want that library to perform.</p><p>What we want to do is come up with some kind of contract. The contract will describe how our business logic wants to interact with this third-party library, so we can abstract it away. To do this, we need to come up with said contract. In many languages, this would be an interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53550ed965edd7d8bcc8638b2cf9e2ee/href">https://medium.com/media/53550ed965edd7d8bcc8638b2cf9e2ee/href</a></iframe><p>In Javascript, since we don’t have classes, (without ES6) we simply describe our contract as a well-documented object. Naming here is very much feature dependent, but it’s preferable to use ‘tell-don&#39;t-ask’ when building out features. Here we tell the reporter exactly what we want it to report by utilizing a descriptive function name, instead of asking for a reporter and then handing it some bit of raw data. This is not always doable, but here it will suffice.</p><h3>Extract</h3><p>Now that we have a contract, we can implement it and have it use ExternalAnalytics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20542d8b913700a36a11a372c1e44ef3/href">https://medium.com/media/20542d8b913700a36a11a372c1e44ef3/href</a></iframe><p>Here, we’ve created a module which contains a single function that returns an object which implements our contract. We can then introduce this into our business logic, replacing our direct usage of ExternalAnalytics with our implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0547887ec31a4155d4939165fc40cf/href">https://medium.com/media/fe0547887ec31a4155d4939165fc40cf/href</a></iframe><p>Now our business logic doesn’t directly depend on a third party library. Rather than being strung through our application, all usage of ExternalAnalytics is encapsulated in a single module. This is a good start, but it’s not perfect.</p><p>In our simple case, we don’t have any dependencies that need to be passed to our reporter method, but that could change. Especially as we want to modify or change what reporter we are using, or perhaps upgrade to a new major version of this reporter. It makes sense now to have a module which encapsulates the creation of this concrete implementation.</p><h3>Inject</h3><p>We can implement a factory, which will remove the responsibility of supplying a reporter with its dependencies from our business logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d3fd707e551cd4be86730c3f465c44/href">https://medium.com/media/27d3fd707e551cd4be86730c3f465c44/href</a></iframe><p>Now that we have this factory, we can use it in our business logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e2c38d9c3eb587c0d6e34016d53180/href">https://medium.com/media/72e2c38d9c3eb587c0d6e34016d53180/href</a></iframe><p>Not only does this allow our business logic to operate and perform reporting without knowing what third-party analytics library it is using, the logic can now do so without needing to know any of the details about the concrete implementation (configuration or otherwise) that it’s using. This means that when we want to change to a new reporting system, it’s very easy to do so. The changes we will need make to our application will be quite minimal.</p><h3>Adding a New Implementation</h3><p>Analytics got back to us and decided to go with AcmeReporting. Since we have all of this infrastructure in place, we simply need to create a new implementation of our contract, using the new third-party library.</p><p>We know that for any implementation we need to do a few things:</p><ul><li>We need to encapsulate the third party analytics library into a new implementation of our contract.</li><li>We need to allow our factory to create instances of this implementation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7771edd8448ad0b349eb8c2645fa262/href">https://medium.com/media/f7771edd8448ad0b349eb8c2645fa262/href</a></iframe><p>Since we are working on this new reporting feature a few months before it will go live, we need a convenient way to turn it off and on. We can do that with a simple config flag, though there are a lot of great ways to accomplish this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e578491244c3ed594f3302957a22a2ef/href">https://medium.com/media/e578491244c3ed594f3302957a22a2ef/href</a></iframe><p>We then need to update our factory with our new implementation, specifying whether to use it or not, by referring to our config.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9482cd2c5f869ef0e14574ae27576f8/href">https://medium.com/media/e9482cd2c5f869ef0e14574ae27576f8/href</a></iframe><p>And that’s it. Our business logic doesn’t need to change at all because all it cares about is getting an object back that contains a reportStart and reportStop method.</p><h3>When should I use something like this?</h3><p>One very good question that has come up about this pattern is when it should be utilized. Such a trivial example as this is easy to come up with, but it’s best to think about real-world examples as well.</p><p>My answer to this question is that we need to consider the entity responsible for a given feature and make a decision as to whether we should isolate it. For example, I don’t think that doing something like this with logging is a good idea. The developers own the logging tool, and it’s purely for developer usage. It will not affect the product in the long run.</p><p>On the other hand, something like a payment provider, analytics library, or another tool which has business value, or can change with respect to the needs of the business the software is being developed for, are all great cases for when something like this should be applied. If the entity in charge of your feature can make decisions about that feature, you are best off isolating it. This article tries to illustrate that example via an Analytics team requesting the utilization of a different library.</p><p>Another good case is for isolation of stochastic operations when performing unit tests, as it’s best to keep these as fast and deterministic as possible. Unit tests which require an internet connection can be very flaky and fail randomly. It’s best to stick with offline testing as much as possible, in order to have the greatest confidence in your tests. In our case, we could implement a test reporter implementation, that is returned if some config has isInUnitTest or some similarly named variable set to true.</p><h3>Conclusion</h3><p>Legacy code is a thorn in the side for any developer. Smart use of design patterns and a clear understanding of the role of each piece of code you write will help strengthen the integrity of the software you produce. Testing is always important, and I recommend you check out the books I mentioned in the introduction of this post.</p><p>If you have questions or comments, you can add them below or reach out to me directly on Twitter <a href="https://twitter.com/Exallium">@exallium</a>.</p><h3>Links</h3><p>Original article: <a href="https://proandroiddev.com/abstract-extract-inject-fcf4b7fed1a8">https://proandroiddev.com/abstract-extract-inject-fcf4b7fed1a8</a></p><p>Github of code examples: <a href="https://github.com/exallium/abstract-extract-inject-js-samples">https://github.com/exallium/abstract-extract-inject-js-samples</a></p><p><a href="https://www.redspace.com/?utm_source=Medium&amp;utm_medium=Boiler%20Plate&amp;utm_campaign=abstract_extract_inject"><em>REDspace</em></a><em> is a full-service digital studio specializing in web, mobile, gaming, and video solutions. We craft digital experiences that empower our clients, helping deliver their content to their audiences. </em><a href="https://www.redspace.com/"><em>redspace.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5583bc79f83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/well-red/abstract-extract-inject-c5583bc79f83">Abstract / Extract / Inject</a> was originally published in <a href="https://medium.com/well-red">Well Red</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract / Extract / Inject]]></title>
            <link>https://proandroiddev.com/abstract-extract-inject-fcf4b7fed1a8?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcf4b7fed1a8</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[legacy-code]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 07:41:01 GMT</pubDate>
            <atom:updated>2018-08-17T07:41:01.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cTfAE8tIjUE6GFIYsrVTWg.png" /><figcaption><a href="http://updates.clipsal.com/assets/images/products/C000258913.PNG">http://updates.clipsal.com/assets/images/products/C000258913.PNG</a></figcaption></figure><p>Legacy code is a part of life for any software developer. There are many definitions of Legacy code. Some consider it to be code that you’ve written. Some consider it to be code that has been released. Whatever the definition, we need to deal with it, whether that involves fixing bugs or building out new features.</p><p>What I would like to describe in this post is a short description of one approach for the introduction of new features into a legacy code base. This strategy works equally well in code bases which manage multiple flavors. Say, for instance, you have one code base that produces two applications. Application A should have Feature X, and Application B should have Feature Y. Using this method, you can enable or disable these features independently of each other. Furthermore, if Feature X is a predecessor of Feature Y, it is possible to then apply this strategy to enable Feature Y or fall back on Feature X through the same pattern.</p><p>A lot of developers already know what I am talking about, Continuous Integration and feature flags. In this case, we deal in the abstract. Feature flags aren’t necessarily some config value that you set on a remote server, though they could be. Instead, I like to think of a Feature Flag simply as a boolean. Either a feature is on or off. It is present, or it isn’t. This approach utilizes composition and the strategy pattern via a factory to provide the proper behavior of our software at runtime.</p><p>There are two parts that we need to think about. Part one is preparing the legacy code to be replaced or modified. Part two is introducing the new code behind a flag.</p><p>This post utilizes tools and terminology from Android development, and is aimed towards those developers. Code Snippets are in Kotlin.</p><h3>Setup</h3><p>Say I have the following code:</p><pre>class MyActivity : AppCompatActivity() {<br>    override fun onCreate() {<br>        featureXDoSomething()<br>    }<br> <br>    override fun onResume() {<br>        featureXDoSomethingElse()<br>    }   <br>}</pre><p>Where featureXDoSomething and featureXDoSomethingElse are just private functions in our activity, operating a particular feature of our software. Perhaps it calls into our model to fetch some data, perform some kind of tracking, or whatnot. Our product team comes back to us, and gives us some different requirements, which they wish to release two versions from now. Not exactly agile, but what are you going to do.</p><h3>Abstract</h3><p>First, we must abstract our feature away from our Activity. What I mean by this is simply, we must take a look at the building blocks of our system and decide how best to introduce this new feature. This can be a complicated thing, but to put it simply, we must decide and define the interface against which this feature works. One such interface could look like so.</p><pre>interface FeatureX {<br>    doSomething()<br>    doSomethingElse()<br>}</pre><p>In this interface, we’ve named our Feature, and given it some actions to perform. Naming here is tricky, but highly dependent on the feature being implemented. It’s good to remember that interfaces are to be defined by the consumer. In this case, we could argue that this interface should be inside MyActivity, so we would infact have MyActivity.FeatureX, with methods called onResume and onCreate to match the call-sites of the original feature methods. A discussion for another time.</p><p>Regardless, we now have an abstraction that aptly describes what or when our feature should act.</p><h3>Extract and Inject</h3><p>Now that we have this interface, we can extract the code from the Activity, into an implementation of this interface, and then inject the implementation into our activity:</p><pre>class OldFeatureX(/* dependencies */) : FeatureX {<br>    override doSomething() { /* code from doSomething */ }<br>    override doSomethingElse() { /* code from doSomethingElse */ }<br>}</pre><pre>class MyActivity : AppCompatActivity() {</pre><pre>    @Inject lateinit var featureX: FeatureX</pre><pre>    override fun onCreate() {<br>        featureX.doSomething()<br>    }<br> <br>    override fun onResume() {<br>        featureX.doSomethingElse()<br>    }   <br>}</pre><p>Of course, we will update our dependency injector as necessary. Since we are introducing a new feature, we will want to put this interface behind a Factory, applying the Strategy pattern:</p><pre>object FeatureXFactory {<br>    fun create(/* dependencies */): FeatureX <br>        = OldFeatureX(/* dependencies */)<br>}</pre><p>This will make the next step easier. We should now be able to test our application and verify that we’ve not yet changed any behavior.</p><h3>New Feature</h3><p>As the name implies, we can then implement our new feature, as an implementation of our interface. We can also add new methods to the interface as requirements could have changed.</p><pre>class NewFeatureX(/* dependencies */) : FeatureX {<br>    override doSomething() { /* new feature impl */ }<br>    override doSomethingElse() { /* new feature impl */ }<br>}</pre><p>We can then add a BuildConfig variable to our gradle files via buildConfigField like so:</p><pre>android {<br>  defaultConfig {<br>    buildConfigField &#39;boolean&#39;, &#39;NEW_FEATURE_X&#39;, &quot;<strong>false</strong>&quot;<br>  }<br>}</pre><p>And then we can update our factory:</p><pre>object FeatureXFactory {<br>    fun create(/* dependencies */): FeatureX <br>        = if (BuildConfig.NEW_FEATURE_X)<br>              NewFeatureX(/* dependencies */)<br>          else OldFeatureX(/* dependencies */)<br>}</pre><p>Now we can simply enable or disable the flag for any of the variants we have, or all of them. In the future, we can refactor and remove the old feature completely, once we fully embrace the new behavior. Furthermore, if product changes their mind again, we have a very simple mechanism to ether swap back, disable the feature completely, or swap in something entirely new, because you’ve already done the groundwork.</p><h3>Conclusion</h3><p>Legacy code is a thorn in any developer’s side, but through smart usage of the Dependency Inversion Principle, Strategy Pattern, and Dependency Injection, the introduction of Feature Flags into Legacy codebases can become a lot safer and simpler.</p><p>This example was fairly trivial. In some cases, you will end up with multiple sets of interfaces, implementations, and factories. However, I think if you step back and look at the bigger picture, and make sure you follow Single Responsibility Principle, you might find that everything can start to come together.</p><h3>Alternatives</h3><p>I think this approach is quite reminiscent of Martin Fowler’s advice in <a href="https://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=sr_1_1?ie=UTF8&amp;qid=1534275671&amp;sr=8-1&amp;keywords=refactoring"><em>Refactoring</em></a><em>. </em>However, I’m always interested in hearing opposing viewpoints as long as it remains civil and constructive. If you have an alternative approach you don’t mind sharing, leave it below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcf4b7fed1a8" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/abstract-extract-inject-fcf4b7fed1a8">Abstract / Extract / Inject</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’s ‘Nothing’ Type]]></title>
            <link>https://proandroiddev.com/kotlins-nothing-type-946de7d464fb?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/946de7d464fb</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Sat, 09 Dec 2017 14:59:30 GMT</pubDate>
            <atom:updated>2017-12-09T14:59:30.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeTrBY19Nefa9YpF7989TQ.jpeg" /><figcaption><a href="https://news.nationalgeographic.com/content/dam/news/2016/06/22/stars/stars-space-time.ngsversion.1466616442453.adapt.1900.1.jpg">https://news.nationalgeographic.com/content/dam/news/2016/06/22/stars/stars-space-time.ngsversion.1466616442453.adapt.1900.1.jpg</a></figcaption></figure><p>A colleague approached me a while ago and asked me a question about Kotlin. What was this “Nothing” type, and what was it used for? I did not really have a good answer for him at the time. Since then, I’ve found my answer.</p><h3>Nothing is the Bottom Type</h3><p>In mathematics, bottom (often denoted as _|_) represents the absolute minimum value something can hold.</p><p>When we’re talking about types, we can think of Nothing as being the absolute bottom (leaf) object of any type hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*K0ruKbqU3kYoxh5FifMxzg.png" /><figcaption>Figure 1: Type Hierarchy</figcaption></figure><p>What we can see in this diagram (figure 1) is that Nothing is the opposite of Any. While every object you will work with in Kotlin implicitly extends Any, so to does Nothing implicity extend any object that exists. This makes Nothing the ‘dual’ or opposite of Any.</p><p>So, why is this useful?</p><h3>Covariant Types (an Example)</h3><p>We can use Nothing along with covariant (producer) types to help make our code more concise and expressive. The following is an example of the Nothing type in action. It is of an Either monad, which can exclusively represent one of two types (L or R), and provides methods for mapping over the values it wraps, including a right-biased map and flatMap (by convention) and a very useful either method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e643257e8eeaa9320dc8dc448ad1aa/href">https://medium.com/media/a2e643257e8eeaa9320dc8dc448ad1aa/href</a></iframe><p>Covariance (marking our parameters as out) allows us to utilize nothing in the R and L positions of the Left and Right declarations of the Either monad implemented here (respectively). Our functions all typecheck and are happy. For example, something like:</p><pre>val e = right(42).flatMap(r -&gt; left(Exception())</pre><p>Will happily type-check and compile. We can even rigidly express the type of e and it’s still happy as can be, all thanks to Nothing and covariance:</p><pre>val e: Either&lt;Int, Exception&gt; = right(42)<br>    .flatMap { left(Exception() }</pre><p>You might have noticed that extension methods are being used here for map, flatMap, and so on. This is due to the Covariant typing mentioned above, which produces type-check errors when trying to pass a lambda utilizing the generic types. Extension methods are a quick and easy way around this issue.</p><h3>So what did we actually get?</h3><p>What we end up with is a better, more concise way to express our types. Nothing almost acts like a type hole, similar to utilizing _ in lambda arguments. We can use it in places where we really just don’t care about the type of something. In our case, if we’ve got a Right, we don’t really need to know anything about the error, because it doesn’t exist. On the other hand, if we have a Left, knowledge of the error is necessary, but not so much for the normal value.</p><p>Hopefully this sheds some light on why Nothing exists and how it can be leveraged.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff20c9a%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Ff20c9a%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Ff20c9a%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href">https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946de7d464fb" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlins-nothing-type-946de7d464fb">Kotlin’s ‘Nothing’ Type</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test By Layer]]></title>
            <link>https://proandroiddev.com/test-by-layer-f9b4d0362f3f?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b4d0362f3f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Tue, 26 Sep 2017 18:22:12 GMT</pubDate>
            <atom:updated>2017-09-27T12:03:18.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*w8TxLcWSftqjYhGhuzeziA.jpeg" /><figcaption><a href="http://food.fnr.sndimg.com/content/dam/images/food/fullset/2014/1/7/0/fnd_finished-sprinkle-cake_s4x3.jpg.rend.hgtvcom.616.462.suffix/1389219145597.jpeg">http://food.fnr.sndimg.com/content/dam/images/food/fullset/2014/1/7/0/fnd_finished-sprinkle-cake_s4x3.jpg.rend.hgtvcom.616.462.suffix/1389219145597.jpeg</a></figcaption></figure><p>In the world of Java and Android, Mockito is an industry standard. Many a unit test are written where the very first thing a developer does is add @Mock annotations for each and every dependency the class under test requires. This works, for the most part, as many developers do not seem to follow the simple principle of open/close. This would, in part, state that if a class is not meant for extension, it should be finalized. Doing so results in some awkwardness, it would seem, when it comes to testing, as now we need to do some extra special things in order to get Mockito to work. This is exacerbated in Kotlin, where both classes and methods are closed by default. Your initial reaction might be to open everything up, or to use interfaces anywhere and everywhere, or use the “back door” that Mockito2 gives you to get around this. But Wait! What if there’s a better way?!</p><h3>Mocking your Boundaries</h3><p>Let’s imagine an app which lets you transfer money between customer accounts. We have entities like Customer , Account , and Transaction. We also have some use-cases, such as CreateCustomerUseCase, CreateTransactionUseCase, and so on. You can see where I’m going with this. (Or, you can check out the sample repository at the bottom of this post!).</p><p>Our use-cases interact with the database which holds persisted entities via repository interfaces. Testing these use-cases is pretty simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5742e6503ac47a9692a0dc3e00f9a15e/href">https://medium.com/media/5742e6503ac47a9692a0dc3e00f9a15e/href</a></iframe><p>For each different behaviour we expect, we write an appropriate test. Note the use of mocks here. Since we interact with two repositories, which are interfaces, we can comfortably utilize mocks. These might be implemented into services or gateways, but in any case they would involve reading and writing, and should be mocked out.</p><p>Note as well that we use a real Customer object. This should come as no surprise. They are small, easy to make, don’t require any kind of verification, and ensure us that we’re using valid input data, given a Customer’s information is validated at object construction time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f22b5b5f017c14c370f6e797a021dbc7/href">https://medium.com/media/f22b5b5f017c14c370f6e797a021dbc7/href</a></iframe><p>This has its own set of unit tests, to verify proper enforcement of valid data. Similar tests exist as well for other entities.</p><p>Now, let’s look at a View Model’s unit test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fbfd5e7486d6b6db5aabe32c5b786ee/href">https://medium.com/media/7fbfd5e7486d6b6db5aabe32c5b786ee/href</a></iframe><p>Notice we are still mocking out our repositories, as they exist at the boundary of our system, but we do not mock out the use cases or the entities. We use the real CreateAccountUseCase and verify that our behaviour is as expected. This is good, and gives us deeper insight into our code. Furthermore, our tests respect the fact that CreateAccountUseCase is a finalized class, and is not extensible.</p><h3>Gaining Insight</h3><p>So what does this approach give us? Insight. Let’s imagine that we’ve written a large application, and tested it in this layered manner. Think back to what we learned about clean coding. Our layered architecture is exactly what is prescribed by “Clean” methodology:</p><ul><li>Entities in the center</li><li>Then domain objects</li><li>Then presentation objects</li></ul><p>The View, Services, and Data pieces are not present in our sample application. Our testing follows our clean methodology:</p><ul><li>Entities are tested in isolation, as they only know about themselves and each other.</li><li>Domain objects are tested using real entities, and mocking out inverted dependencies (repositories)</li><li>Presentation objects are tested using real use-cases and real entities.</li></ul><p>What happens now, is that when we make a breaking change in one layer, components in other layers are also effected. This sounds like strong coupling, but it has large benefits.</p><ul><li>You can instantly see, through test failures, which pieces of your code are effected by behavioural changes elsewhere in the system.</li><li>Regressions decrease because of the increased level of code penetration.</li></ul><p>That last point is very important. Doing this means that your outer layers are no longer ignoring the logic of your inner layers, but assuming that it adheres to the contract set in their (the inner layers) own unit tests. If that contract is broken, we get to see the immediate breakage right away. Imagine if, in our last code snippet, we just mocked our responses of our use case instead of using the real one. Now, if the use-case’s behaviour changes, we don’t see this in this test. Perhaps we just update the use-case’s test and move on. This causes a breaking change, and may only get picked up in regression testing, leading to a prolonged release cycle as you scramble to solve the issue!</p><h3>Conclusion</h3><p>I firmly believe that we as developers love new tools. We like to latch on to tech, patterns, etc. and never let go. In the case of mocks, we need to make a decision each and every time we use them, and it’s a decision that a lot of us ignore. “Why is this a mock?” is the question we need to answer, and with that answer then make this decision of whether or not to create a mock. If we can’t think of a great reason other than “because it’s what I’ve done before” or “because it’s a dependency,” then maybe it’s time to take a good hard look at your tests, and decide whether they’re really as robust as they can be.</p><p>Examples of good times to mock are places where you’ve inverted a dependency or where you know IO or other blocking or async actions could be taking place. One last one is when you actually need to be able to verify actions, such as feeding your class under test a callback, and verifying methods are invoked in accordance with expected behaviour.</p><p>Every day, we get opportunities to make our software better and safer, and I think this is an easy step to both of these.</p><p>Here is the sample repository: <a href="https://github.com/exallium/TestingLayers/">https://github.com/exallium/TestingLayers/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b4d0362f3f" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/test-by-layer-f9b4d0362f3f">Test By Layer</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Kotlin Scripts]]></title>
            <link>https://proandroiddev.com/testing-kotlin-scripts-42bbbbe09ae5?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bbbbe09ae5</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Tue, 15 Aug 2017 20:40:57 GMT</pubDate>
            <atom:updated>2017-08-21T16:26:18.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Hd1J5ju0yjiPfRmug7d-A.jpeg" /><figcaption><a href="https://i.ytimg.com/vi/cErKuY3lZcY/maxresdefault.jpg">https://i.ytimg.com/vi/cErKuY3lZcY/maxresdefault.jpg</a></figcaption></figure><p>Recently, I’ve taken it upon myself to do a bit of automation scripting for some of the more tedious day to day tasks I am faced with at work. One such task involves some simple git command parsing and string manipulation, and is very time-consuming. Through some deliberation with my colleagues, I’ve written the script now in several languages in an act to compare them internally. What’s more, one of those languages was Kotlin Script, and testing it was a bit of a bumpy road, but turned out to be quite simple in the end.</p><p>I should make a huge note here that I love Kotlin as a language, and am in no way looking to cast a shadow on just how great it really is. Moreover, I’m trying to give a current state of afairs (note the date given in the conclusion) and perhaps save some people a bit of headache, if they value unit testing their custom tools (which they should!).</p><h3>Other options, and Kotlin</h3><p>In today’s world, there are a myriad of scripting languages that one can choose to write custom tools for. Initially in fact, when I wrote this test script, it was in Python, which is excellent for such things. A colleague of mine then commented on while it looks like the script works, they had no idea as to what was going on! This is of course, because they’re an Android developer, and haven’t ever worked with Python.</p><p>To make mention of it, shell is also a dying alternative. The terse and complex nature of shell’s syntax gives it a sometimes unwieldy barrier of entry, and even some experienced programmers must refer back to syntax guides just to figure out exactly what’s going on. It is quite difficult to write a complex script in any acceptable amount of time, especially when compared to alternatives.</p><p>In Android projects, the most obvious candidate for a scripting language is Groovy. It is what the Gradle build system is configured in by default, and is easily testable via Spock. What’s more, there exists the Gradle TestKit which enables you to write unit tests on Gradle tasks in conjunction with Spock. This was very easy to set up and get running in almost no time at all, and I was able to simply follow my normal GIVEN//WHEN//THEN pattern with a test subject as I would in any other code.</p><p>Enter Kotlin Scripts. As a scripting language, Kotlin is quite immature. There is a very large draw to be able to utilize it as your scripting language, especially if you plan to move application code to Kotlin. Consistency. New developers only need to learn one single language, and suddenly they are empowered to work anywhere in the code base, be it on application code or in custom scripts. Furthermore, first class support and a strict type system allows for better autocompletion and tooling within Android Studio itself. However, issues exist. Some issues with it currently are that you cannot import code from other script files, and cannot run tests on your script directly in any sane manner. Thus, some alternative path is required.</p><h3>Test Setup</h3><p>Setting up unit tests is quite simple. The following is an example hierarchy for a script and its tests.</p><pre>tools/MyScript.kts<br>tools/tests/MyScriptTest.kt<br>tools/tests/build.gradle</pre><p>Our build.gradle file is a normal Gradle file with the Kotlin plugin applied, as documented <a href="https://kotlinlang.org/docs/reference/using-gradle.html">here</a>. We also apply JUnit as a dependency. Lastly, we apply sourceSets.test.kotlin.srcDirs = [&quot;.&quot;] which will set our source directory for tests to the current working directory.</p><p>We can now implement unit tests as normal, with a simple piece of code to run our command:</p><pre>private fun runCommand(command: String) = Runtime.getRuntime()<br>        .exec(arrayOf(&quot;/bin/sh&quot;, &quot;-c&quot;, command))<br>        .inputStream.bufferedReader().readText()</pre><p>This will run the command given and return it’s output as a String. To run our script, we could call:</p><pre>runCommand(&quot;kotlinc -script ../myScript.kts arg1 arg2&quot;)</pre><p>And then analyze the output and make assertions as necessary. We can then run our tests via the normal means:</p><pre>gradle test</pre><h3>Issues</h3><p>So what are the glaring issues with this? Well, for one, it would be nice to be able to utilize the normal testSubject pattern, where we create an instance of a class and then assert different functionality against it. We can get close, but the solution is currently very complicated. See <a href="https://github.com/JetBrains/kotlin/blob/master/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTest.kt#L40">this</a> file for details. Ideally, this will get a lot <a href="https://github.com/Kotlin/KEEP/blob/scripting/proposals/scripting-support.md">better</a> as time goes on.</p><p>Secondly, and very importantly, testing like this is very slow. Since you need to start up a separate process for each test, you could be waiting up to 5 seconds per test for execution. Mileage on this will of course vary per machine.</p><h3>Conclusion</h3><p>This really isn’t meant to shed negative light on Kotlin Scripts. I think it’s a fantastic idea. But what needs to be remembered is that this is all still experimental, so I wouldn’t rush out and rewrite your scripts into Kotlin just yet. The future is very bright however, and I believe that in 6 months or a year or so, we will have much better support.</p><p>My professional recommendation, if you want to write a large amount of scripts, maintain a fast test suite for them, and be able to share code among these scripts, then your best bet is to probably use Groovy. This language is already being used in your app for Gradle, unless you’re a bleeding edge kind of person and have already moved to Kotlin Scripts for Gradle. If you’re like the rest of us however, your best and most performant experience will be ascertained from Groovy.</p><p>This advice is, of course, predicated on you being an Android developer. If you were utilizing, say, the Django web framework, it would make sense that you would want to implement scripts in Python, to maintain that consistency.</p><p>But who knows, in a year, my opinion could be of a completely different colour.</p><p>Please note this body of work is based off of the state of Kotlin Scripting as of August, 2017.</p><p><strong>Update: A Git Repository illustrating how to set this kind of testing up is located </strong><a href="https://github.com/exallium/kotlin-script-test-sample"><strong>here</strong></a><strong>.</strong></p><p><strong>Update 2: CamelCase is the recommended way to name script files, as you can then refer to the script’s instance utilizing </strong><strong>this@MyScript within them without issues.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bbbbe09ae5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/testing-kotlin-scripts-42bbbbe09ae5">Testing Kotlin Scripts</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android ViewModels means Composition]]></title>
            <link>https://proandroiddev.com/android-viewmodels-means-composition-e305c7427602?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e305c7427602</guid>
            <category><![CDATA[android-data-binding]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 19:06:44 GMT</pubDate>
            <atom:updated>2017-07-06T12:48:40.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xHtYtLduh5SR7Xvo1UuWA.jpeg" /><figcaption><a href="http://hdqwalls.com/download/android-simple-minimalism-wide-1400x900.jpg">http://hdqwalls.com/download/android-simple-minimalism-wide-1400x900.jpg</a></figcaption></figure><p>With Google’s new ViewModel library comes a new slew of tutorials, documentation, blog posts, and github repositories describing it’s uses and how to get it up and running. One gigantic thing I think a lot of people miss in these tutorials is one of the core concepts of MVVM, composition.</p><p>The full code for this post in a fully runnable sample app can be found <a href="https://github.com/exallium/CompositionExample">here</a>.</p><p>Composition allows us to create something that is greater than the sum of it’s parts. For example, let’s imagine for a moment that I have the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*SZaRHac4NM9gCaSW6Nb0XA.png" /><figcaption>Fig. 1: Composition Sample Application</figcaption></figure><p>Notice that we can break this screen down into several different parts:</p><ul><li>The Header (Toolbar)</li><li>The Content (Middle Section)</li><li>The Footer (Bottom bar)</li></ul><p>Each of these components perform different tasks, and each one can have it’s own ViewModel object where these tasks are performed. Doing this allows for a few niceties:</p><ol><li>Great Separation of Concerns. Each ViewModel is small, focused, and easy to digest.</li><li>Easy testability, again due to the small, isolated nature of ViewModels.</li><li>Reusability / modularization. By segregating presentation logic for different components, we now have reusable components. For example, it is trivial now to use the same toolbar on multiple pages.</li><li>Minimization of Activity Logic. Our activity becomes a dependency injector / router for our application, and nothing more. This makes testing it almost completely unnecessary, besides some minor UI tests to verify we go where we expect when we interact with the bottom bar.</li></ol><p>So how do we wire all of these together? Utilizing Android Databindings, we end up with the following binding pairs:</p><ul><li>main_activity.xml / MainActivityBinding</li><li>page1.xml / Page1Binding</li><li>toolbar.xml / ToolbarBinding</li><li>bottom_bar.xml / BottomBarBinding</li></ul><p>We end up with the following ViewModels:</p><ul><li>Page1ViewModel</li><li>ToolbarViewModel</li><li>BottomBarViewModel</li></ul><p>Note that Page 2 does not have a ViewModel or Binding. This is because it is just a simple text view, and does not require one.</p><p>Our MainActivity XML file looks like such:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2cf433417c79f18fb9bc92b73ce2a1/href">https://medium.com/media/4a2cf433417c79f18fb9bc92b73ce2a1/href</a></iframe><p>Note our use of the include tag, along with an ID on each of these tags. This will allow us to inject child bindings into our generated MainActivityBinding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a9171cfe8f275931fd544b264f5ce19/href">https://medium.com/media/4a9171cfe8f275931fd544b264f5ce19/href</a></iframe><p>Our Main Activity is as noted earlier. It provides dependencies to it’s ViewModels and some routing code. In this sample application, we avoid Dagger altogether, and instead lean on the ViewModels acting like singletons with respect to a given Activity, since this is all we really need.</p><p>Note that the addition of IDs to the include tags has automatically set up multiple view bindings within our layout, and we simply need to set our ViewModels up.</p><p>The ToolbarService here is a ViewModel which simply allows different ViewModels to inform the Toolbar as to what it should display. The other route here is of course to allow ViewModels to talk directly to each other, but I deviated from this and followed closer what is done in frameworks like AngularJS, purely for educational purposes. This can be viewed as an over-abstraction, and is perfectly fine to leave out.</p><p>This singleton pattern for ToolbarService could also be applied via a normal Dagger injection. One way is to make the factory itself injectable, and then simply provide the right ViewModel via a Provider as they are requested. This would allow Dagger and the ViewModelProviders to work happily together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92db088b03662cc406e0a651ea2adb26/href">https://medium.com/media/92db088b03662cc406e0a651ea2adb26/href</a></iframe><p>Due to the nature of ViewModels, we can safely open the app on a device and see that rotating the display will leave you exactly where you expect, and all state is maintained and respected.</p><p>For more information on some of the nitty gritty details around factories and the like, I’d refer you happily to the article here, by a colleague of mine: <a href="https://proandroiddev.com/architecture-components-modelview-livedata-33d20bdcc4e9">https://proandroiddev.com/architecture-components-modelview-livedata-33d20bdcc4e9</a></p><blockquote>Utilizing multiple models per screen helps build modular, finely grained, testable, maintainable applications for you and your users.</blockquote><p>Hopefully through this process I’ve sparked some intuition about how ViewModels can be viewed and treated. Utilizing multiple models per screen helps build modular, finely grained, testable, maintainable applications for you and your users. It can help relieve the headache of large source files, and can help to maintain a cleaner code base throughout a long, large project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e305c7427602" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-viewmodels-means-composition-e305c7427602">Android ViewModels means Composition</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional MVVM on Android]]></title>
            <link>https://medium.com/thoughts-from-exallium/functional-mvvm-on-android-cd6c6cb07e06?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd6c6cb07e06</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 19 Apr 2017 17:58:23 GMT</pubDate>
            <atom:updated>2017-04-25T16:15:38.320Z</atom:updated>
            <content:encoded><![CDATA[<p>This post serves as a rewrite for a previous post of the same title. The original post was a little too full of theory, so I made the decision to distill it down to it’s core, and try to present a concise overview of what MVVM is, how to make it functional, and why I think it is important with respect to a scalable Android application.</p><h3>Agenda</h3><p>In this post, I plan to cover the following topics.</p><ol><li>Definition of MVVM and Reactive Programming</li><li>Android Databinding</li><li>Android Databindings and Rx Interop</li><li>Unidirectional Flow of Data</li></ol><h3>MVVM</h3><p>MVVM stands for Model-View-ViewModel, and is a design pattern which tries to maintain a very low level of coupling between each component. It is very similar to the more well known MVP (Model-View-Presenter) but with a single glaring difference, being the ViewModel itself. Instead of a Presenter which is injected with a View interface, there exists a ViewModel which the View can observe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*jegnbK1ueVONi-zPFS_Sog.png" /><figcaption>MVVM</figcaption></figure><p>What really ends up separating this from MVP is that the View, be it an Android Activity or otherwise, does not need any information about the ViewModel or the View it happens to be inflating. It simply gets injected with a ViewModel which it instantly binds into the Android Databinding object, which we will come back to later.</p><p>What this allows for is a flexible, scalable system. A single Activity could be comprised of multiple Views, or multiple ViewModels, none of which are the wiser about each other. This makes for very reusable screen components and ViewModels alike. For example, I could utilize the exact same View XML and ViewModel for every toolbar in my application, and combine it on a screen with another View and ViewModel which then represents a login form or some other piece of UI.</p><h3>Reactive Programming</h3><p>Reactive Programming is an enormous topic, so I don’t want to try to fully explain what it is in a couple of paragraphs. Suffice to say, is that Reactive programming means that we will work with asynchronous streams of data, in a way which allows for composition and other functional utilities, like mapping and reducing data. If you are not familiar with reactive programming on Android, I encourage you to take a look at RxJava, as it will greatly aide you through the rest of this post.</p><h3>Android Databinding</h3><p>Android Databinding is a relatively new library that allows us to tie callbacks, observable fields, and other things directly into attributes in our layout XML. This is a great fit for the MVVM model, as it allows then for whomever is hosting the View the layout inflates into to be as ignorant of the inner workings of the View and it’s relationship to the ViewModel as possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006f2525aadd86b1a18916549bd9e32f/href">https://medium.com/media/006f2525aadd86b1a18916549bd9e32f/href</a></iframe><p>Note in the above example, the use of the “@{}” syntax, which gives me access to different fields on the ViewModel. The &lt;variable&gt; tag lets me specify what my ViewModel is. The attributes utilizing Android Databinding in this example are all custom, and will be brought up again in the section about Rx Interop. More information on Android Databinding can be found <a href="https://developer.android.com/topic/libraries/data-binding/index.html">here</a>.</p><h3>Android Databinding and Rx Interop</h3><p>As you probably guessed, “app:bindTextChanges”, “app:bindError” and “app:bindClicks” are all custom attributes. These all map to binding adapters within the host application.</p><p>Bind Error is probably the simplest of these. It is set up to watch an observable field, viewModel.firstNameError for example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6d6e9d0e4605bb9df4be50b5234656/href">https://medium.com/media/7c6d6e9d0e4605bb9df4be50b5234656/href</a></iframe><p>In this example, we’ve created a new BindingAdapter which will be applied to “bindError” attributes. We do not have to specify “app” here, and we will get a warning about it being ignored if we do. This function takes two arguments, the view to bind to, as well as the error string, and then updates the TextInputLayout error field and visibility as necessary.</p><p>The other two, text changes and clicks, utilize Jake Wharton’s library <a href="https://github.com/JakeWharton/RxBinding">RxBinding</a>. Utilizing a Consumer interface, we can hand the ViewModel an observable stream of text changes or clicks. Note that the “StringConsumer” and “ClickConsumer” here are necessary, due to a bug which strips out generic type information when the databinding classes are generated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/797d00420a9ef80b459dc5a201bfbee1/href">https://medium.com/media/797d00420a9ef80b459dc5a201bfbee1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3d4c01396dbd61f8c3d7a7d2243f3e8/href">https://medium.com/media/c3d4c01396dbd61f8c3d7a7d2243f3e8/href</a></iframe><p>Doing this gives me a very straightforward way to utilize this information within my ViewModel, who shouldn’t really know about Android Views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed866950e08cdb6a8f6c35098d63ba65/href">https://medium.com/media/ed866950e08cdb6a8f6c35098d63ba65/href</a></iframe><p>Note here, we utilize Jake Wharton’s RxRelay library for relaying these interactions to our Model. The model in this case just propagates onNext events to UseCases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8ba3fc69d95f0dc7dd2902b0881c7b/href">https://medium.com/media/8e8ba3fc69d95f0dc7dd2902b0881c7b/href</a></iframe><p>Each UseCase implements ObservableTransformer, taking in whatever it needs, and returning a UseCaseResult, which is an empty interface which Results extend, and allows for all of these interactions to have their results merged back together. This idea comes straight out of a recent talk from Jake Wharton, found <a href="https://www.youtube.com/watch?v=0IKHxjkgop4">here</a>.</p><p>In it, he talks a lot about our next point of discussion.</p><h3>Unidirectional Flow of Data</h3><p>This UseCaseResult seems a bit weird at first, but there is actually a good reason for it. What it allows for is a single, continuous flow of data through the system. From our handlers, into our UseCases, and back into our ViewModel, who then updates the View’s state accordingly via ObservableFields and other events. Each UseCase implements it’s own set of results, and then the ViewModel is free to pick and choose which ones it cares about. For example, the following is a UseCase which will validate a user’s first name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e70546438e93ffeb25f3d7437d8b17c0/href">https://medium.com/media/e70546438e93ffeb25f3d7437d8b17c0/href</a></iframe><p>The InProgress doesn’t make a lot of sense in this case, but imagine a scenario where we need to check a username vs. a database of usernames for uniqueness. As soon as we introduce any kind of blocking action into the stream, the InProgress Result becomes necessary, as it allows us to see that progress is happening within the subscriber in the ViewModel, and set up any loading indicators or other things as necessary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/468c8d8e43971d87ff209953a5216388/href">https://medium.com/media/468c8d8e43971d87ff209953a5216388/href</a></iframe><p>The ViewModel will subscribe to all of the UseCaseResults through the same subscriber, and can process them through there. Since everything is done by type, and the type breaks down through a few hierarchies, this is a very easy function to split up however you wish.</p><p>You could make the case to keep the streams for each Input/UseCase pair separate, as this could quite quickly become hard to maintain. It’s really up to you. In that case, the Model would most likely disappear.</p><p>Regardless, it is important to note the Unidirectional Flow of Data here:</p><ol><li>User Changes First Name Text</li><li>Change Event is fired</li><li>UseCase validates event, firing an InProgress signal in the meantime</li><li>ViewModel updates View State appropriately</li><li>UseCase eventually fires Success or Failure</li><li>ViewModel updates View State appropriately</li></ol><h3>Conclusion</h3><p>Utilization of MVVM and following the principle of unidirectional flow of data can help keep your View class from knowing too much about the layout or the ViewModel. This can be very helpful when designing reusable components, and helps to make for a flexible, reactive, and scaleable system.</p><p>By following the flow presented here and within the <a href="https://github.com/exallium/mvvmexample2">sample application</a> you can create a simple, easy to follow, and easy to test application which encourages data immutability, unidirectional flow, and functional purity.</p><p>Oh, and go watch Jake’s video!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd6c6cb07e06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/functional-mvvm-on-android-cd6c6cb07e06">Functional MVVM on Android</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monoids: It’s just Reduce!]]></title>
            <link>https://medium.com/thoughts-from-exallium/monoids-its-just-reduce-9248334ba5e7?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9248334ba5e7</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 19:37:40 GMT</pubDate>
            <atom:updated>2017-01-17T19:41:29.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Oversimplifications happen to be something I’m good at, so I’ll apologize in advance if this is another one. A lot of the time when people approach a language like Haskell, they start seeing big scary words, like “Monad” and “Monoid”. Well, I’m here today to try to enlighten you for the latter. Monoids, as it turns out, are just units you can reduce <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphically</a>. There’s another big word, so let me break this down in a way that should be understandable.</p><p>Monoids require two basic functions, and follow a few rules. In Haskell, these functions are called memptyand mappend. The former is essentially an identity function, and the second is an <a href="https://en.wikipedia.org/wiki/Operator_associativity">associative</a>, binary operation. A very simple example of this is summation. The Sum Monoid would contain functions for the identity and apply for summing two numbers together. Simply, 0and add . We could define a Product Monoid as well, which would have the identity 1 and append function multiply.</p><p>It should be clear here in these two simple examples, the intended functionality of these functions. Monoids include a type of some kind. In our example, the type is some variant of numbers. Numbers have two associative operations, so we distinguish between them by their names. The identity function of each of these monoids, if it was applied within the append function, would result in an output the same as it’s other input:</p><p>mappend mempty x = x</p><p>This is one of the laws of Monoids. It becomes pretty simple if you replace mappend with add and mempty with 0.</p><p>So, what we’re really able to do with Monoids is take two values of a given type, and mappend them down into a single value. This is, simply, a reduction.</p><p>This idea of an associative binary operation and identity function is very generic. Think of Monoid as an interface (it is, after all, a class in Haskell, which is it’s analog to an interface in languages like Java or C#). If we have a type, T, we can describe it in terms of Monoidial combination as long as:</p><ul><li>We can define an associative binary operation that takes two T’s and returns a T</li><li>We can define an identity element such that mappend mempty x = x</li></ul><p>This is a hugely powerful concept. We can define Monoid in almost any language, and use it as a container to perform reduction operations on, allowing us to quickly build up reduction operations, reduce over sets of Monoids, etc. What’s more, this is scalable. If we can define our problem in the Map-Reduce sense, and utilize the Monoidial structure, we end with a solution that can be spread across multiple cores, multiple machines, etc.</p><p>Here’s an example of a Monoid in Kotlin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1056871c51ae5cce97ff0dcb96f988cc/href">https://medium.com/media/1056871c51ae5cce97ff0dcb96f988cc/href</a></iframe><p>Note here how reduce doesn’t know anything about how a ValidationResult is reduced, only that it can be, because it’s class object is a Monoid. In this simple example, we are validating the length of all of the strings inside of strings and printing the reduced result.</p><p>How do you apply this? Simple. Next time you’re building anything, start asking yourself. How do these things combine? How could I identify an Identity here? What flexibility does this provide me?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9248334ba5e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/monoids-its-just-reduce-9248334ba5e7">Monoids: It’s just Reduce!</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive MVP in Android]]></title>
            <link>https://medium.com/thoughts-from-exallium/reactive-mvp-in-android-2d4a934c3874?source=rss-c9aafad647d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4a934c3874</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 04 Jan 2017 17:56:10 GMT</pubDate>
            <atom:updated>2017-01-04T17:56:10.471Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve looked at a lot of different implementations of the MVP pattern within Android applications over the last year. Some I agree with, and some I don’t. Today, I had a thought about the pattern I currently use, and thought that I would share that implementation in it’s current state.</p><h3>What Is MVP</h3><p>I guess that this is the question I should answer first. MVP stands for Model View Presenter, and is a refinement of Model View Controller. The more popular approach that you will see today is called Passive-View MVP. The View is as dumb as possible, which boils down to basic view bindings and click handlers. Clicks are forwarded to the presenter, and data is set by the presenter.</p><p>The Presenter contains all of your presentation logic for mediating displaying data, fetching data, and the like between the view and the model. It is where we try to contain all of our logic, and the primary focus when we unit test.</p><p>The model can be a few different things. It could be a collection of objects injected into your presenter with a tool like Dagger, or it could be a single interactor defined within your component, which itself is injected with backend classes. A good rule of thumb here is to give yourself an upper limit of model classes you are willing to inject into your presenter before you utilize an interactor. This way, you maintain the ability to keep code easy to understand, as well as easy to maintain. Abstraction for the sake of abstraction can increase complexity when it’s unnecessary.</p><h3>The Role of a Model / Interactor</h3><p>There is a common pattern of thought that states that all of your logic should be contained within your presenter. I tend to disagree with this sentiment a little. When we think of SOLID software, we often think of having a class do exactly one thing very well. Which, from a high level, makes a lot of sense. The presenter takes care of business, the model provides data, and the view shows it. However, I think that we can split logic up into two different sections, domain logic and presentation logic.</p><p><em>Domain logic</em> concerns itself with “what” data is being displayed. <em>Presentation logic</em> concerns itself with “how” that data is displayed. The view, of course, has no logic, and just happens to denote “where” something is displayed. I suppose then, in the Uncle Bob sense, my Model feels more like an Interactor than a model, though I tend to use these things fairly interchangeably. It should be noted that the presenter still controls “what” data it’s pulling from the model, if given multiple options. The model would simply expose these choices as different methods. That being said, any data manipulation or other wiring that involves providing the presenter with exactly what it is asking for becomes a task for the model.</p><h3>The State of the World</h3><p>I read a lot of code. Both from people I may be interviewing, or random code I find on reddit, or code at work that I am involved in developing. There is a very common MVP pattern where each of these three M, V, and P are Interfaces, implemented by concrete classes. Either that, or they exist as Abstract classes. The View will get a reference to the presenter, and the model will either also get a reference to the presenter, or provide its own Callback or Listener interface for which it is the responsibility of the presenter to implement. Note that in the case of the callback interface, the presenter interface is then only utilized by the view. I find this to be a bit inconsistent. Moreover, I find that the necessity of the View knowing anything about the presenter to oppose my desire to make it as dumb as can be. Surely, we can isolate ourselves to a point where the Model and View know nothing about each other or the presenter, but only how to take in information and provide information. Be it the result of a Database query, or a tap on a button. This is where ReactiveX comes in.</p><h3>ReactiveX as a Boundary</h3><p>Thus, I propose utilizing ReactiveX as a boundary between these three layers. There are actually several reasons to do so, but the foremost is that in all of these MVP implementations, suddenly the P interface goes away. We only need M and V, and these are injected into the Presenter in runtime.</p><p>The View, who’s views may be bound with a tool like Butterknife, now just provides methods by which someone can subscribe to clicks.</p><p>The Model simply provides methods by which someone can subscribe to data fetches.</p><p>And all of the error handling is “Free”</p><p>Furthermore, given we are now in Rx land as soon as someone clicks a button, we have a massive amount of operators at our immediate disposal. We can initiate a database save via a simple flatMap, or we can dismiss our current screen or show a validation error. We can debounce clicks, and map data into our views, all reactively.</p><p>Testing is still simple. We can utilize <em>TestSubscriber</em> from RxJava to ensure the right flows of behaviour occur. We can set up chains of clicks or different data sets to see how our presenter reacts. And since we use this on both sides of our interactor, we are also able to verify that any data massaging it does is done as well, in the exact same manner.</p><h3>Sample</h3><p>This is a small sample of what I am going on about.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeb98dc2c22b12075a019f6cd230440e/href">https://medium.com/media/aeb98dc2c22b12075a019f6cd230440e/href</a></iframe><p>There are a few things here missing, such as unsubscribing, but I think it is enough to illustrate the point. There is an argument to be made about making the view reactive as well, but I think you’ll eventually overcomplicate it. Allow the Presenter to be both your Active and Reactive component. It initiates data requests, handles thread scheduling, and handles passing data between the view and the model. The model handles talking to the database layer, and perhaps any extra filtering on the returned data that the presenter doesn’t need to concern itself with.</p><p>I’m interested in feedback about this approach, but remember to keep it constructive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4a934c3874" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/reactive-mvp-in-android-2d4a934c3874">Reactive MVP in Android</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>