<?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 Antonio Gutierrez on Medium]]></title>
        <description><![CDATA[Stories by Antonio Gutierrez on Medium]]></description>
        <link>https://medium.com/@czyrux?source=rss-ba532f5866b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S48JVmZmzKrZ2TZGBtzfPA.jpeg</url>
            <title>Stories by Antonio Gutierrez on Medium</title>
            <link>https://medium.com/@czyrux?source=rss-ba532f5866b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 04:35:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@czyrux/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[State propagation in Android with RxJava Subjects]]></title>
            <link>https://proandroiddev.com/state-propagation-in-android-with-rxjava-subjects-81db49a0dd8e?source=rss-ba532f5866b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/81db49a0dd8e</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Antonio Gutierrez]]></dc:creator>
            <pubDate>Wed, 09 Nov 2016 18:21:04 GMT</pubDate>
            <atom:updated>2018-05-30T08:50:59.228Z</atom:updated>
            <content:encoded><![CDATA[<p>When working in Android projects, it is quite common to have different pieces of your application that need to react or get updated when something occurs somewhere within your UI or application. This problem, that in principle may look quite simple, quickly gets out of hands.</p><h3>A common solution: Event Buses</h3><p>A very common approach is to use an Event Bus (<a href="https://square.github.io/otto/">Otto</a> or <a href="http://greenrobot.org/eventbus/">EventBus</a> are good options in Android). In this approach, the component that notices the action will post an event that other components needs to react to. Code looks something like this:</p><pre>// At the source<br>bus.post(new AvailableEvent(42));</pre><p>Somewhere else…</p><pre>public somewhere() {<br>    // blabla<br>    bus.register(this);<br>}</pre><pre>@Subscribe <br>public void onAvailableEvent(AvailableEvent event) {<br>    // React to the event somehow!<br>}</pre><p>This approach has worked fine for me in the past but I was never fully happy with it. In my experience this approach can get quickly out of hands and is error prone, producing the so called <em>event-madness:</em> Events send multiple times from different sources, events that nobody listen for, are never posted, or get lost due to UI not being subscribed at the moment of posting.</p><p>And for me the more important handicap, the traceability of the code. At the moment of writing the code everything is clear and looks like a clean solution, but come back a week later and you will be scratching your head about who is creating the event and under which conditions. This is especially problematic in large code bases with several people contributing or when multiple events are linked together.</p><h4>Broadcast Receivers</h4><p>An alternative to event buses are <a href="https://developer.android.com/reference/android/content/BroadcastReceiver.html"><em>Broadcast Receivers</em></a>. They follow a similar idea and have the same problems as buses, but are way more cumbersome and require your payloads to work on <em>Intents (extras keys, Parcelable interfaces, etc.)</em> <em>-.- Lets move on</em>…</p><h3>In the search of something better: Using Subjects to propagate state</h3><p>In this post I want to explore how we can use <strong><em>RxJava</em></strong> <strong><em>Subjects</em></strong> to achieve the functionality required, overcoming some of the issues appearing in other solutions. But before building the components that help us share state across the app, lets see what <em>Subjects </em>are and how to work with them.</p><blockquote>Note: I will not be covering the basics of RxJava in this blog, so a familiarity with the core concepts is recommended.</blockquote><h4>A (very) quick intro to Subjects in RxJava</h4><p>I do not pretend to give a full explanation about RxJava Subjects, you can find proper definition in the <a href="http://reactivex.io/documentation/subject.html">official docs</a> and this great <a href="https://akarnokd.blogspot.de/2015/06/subjects-part-1.html">blog post</a> from David Karnok.</p><p>But in a nutshell, <em>Subjects</em> is a sort of bridge or proxy that acts both as an <em>Observer</em> and as an <em>Observable. </em>That means that it is an object that clients can chain onto it (<em>Observable</em>), and can also emit values and terminal events as well (<em>Observer</em>). In particular we are gonna pay special attention to two of the available subjects: <strong><em>BehaviorSubject </em></strong>and<strong><em> PublishSubject.</em></strong></p><h4>Thread Safety</h4><p>When working with Subjects, you need to be aware of who is pushing content and from where. In our case, we may expect updates to come from different threads. And here is the problem, all Subjects are <strong><em>NOT thread safe</em></strong>, except <em>SerializedSubject</em>. In order to solve our problem and convert a subject in a thread safe version, we can call S<a href="http://reactivex.io/RxJava/javadoc/rx/subjects/Subject.html#toSerialized%28%29"><em>ubject#toSerialized()</em></a></p><blockquote>For an in-deep explanation about thread safety issues in Subjects check this <a href="https://artemzin.com/blog/rxjava-thread-safety-of-operators-and-subjects/">post</a> by <a href="https://medium.com/u/4600c10f9c5a">Artem Zinnatullin</a>.</blockquote><h4>Going a step further: RxRelay</h4><p><em>Subjects</em> are stateful in a dangerous way: when they receive an <em>onComplete or onError</em> they no longer become usable for sharing data. <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a> created a library to solved this problem <a href="https://github.com/JakeWharton/RxRelay">RxRelay</a>. From the repo README: A <em>Relay</em> is a <em>Subject</em> without the ability to call <em>onComplete</em> or <em>onError</em>. This makes them perfectly suitable for our task, sharing data. It contains equivalent construct for each of the <em>Subjects</em>: <em>BehaviourRelay</em>, <em>PublishRelay</em> and <em>ReplayRelay. </em>There is no version of <em>AsyncSubject </em>since there is no termination events on<em> Relays.</em></p><blockquote>A <em>Relay</em> is a <em>Subject</em> except without the ability to call <em>onComplete</em> or <em>onError</em></blockquote><h3>A first approach: RxBus</h3><p>Our first solution would be based on <strong><em>PublishSubject</em></strong>. We can implement a bus relatively easily with one of them.. There are several blog posts out there explaining the approach (<a href="http://blog.kaush.co/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/">post1</a>, <a href="http://blog.metova.com/how-to-use-rxjava-as-an-event-bus/">post2</a>). <a href="https://gist.github.com/czyrux/d73503f79c223adfbb7da95dd5b469fe">Here</a> is a simple implementation using Relays:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/951ee1d9d98807bf70fcffd29cf11ba5/href">https://medium.com/media/951ee1d9d98807bf70fcffd29cf11ba5/href</a></iframe><blockquote>Implementation Note 1: upon registration we pass the event class to be notified, in this way we are going to notify only events for the expected class.</blockquote><p>This basically is an implementation of an Event Bus in RxJava and, in my opinion, it does not provide much advantages above a common bus. Surely it improves the code traceability and brings the RxJava goodies (composing operations, thread control, etc.), but still, it looks like we could improve it.</p><h3>A better option: the Store component</h3><p>We can consider a <em>Store</em> like an event bus for a single resource. Store name is inspired by <a href="https://facebook.github.io/flux/docs/overview.html">Flux architecture</a> and the Store concept in there. But unlike the Store in Flux, here it is used only to keep state, no logic.</p><blockquote>We can consider a <em>Store</em> like an event bus for a single resource.</blockquote><p>This idea brings a few benefits over a generic bus.</p><ul><li><em>Single source of truth</em>. Since we are using a single resource, we can use a <em>BehaviourRelay </em>under the hood instead of a <em>PublishSubject</em>, making the last state always available as soon as someone subscribes. This allows us to know the resource state at any given moment.</li><li><em>Scalability and flexibility</em>. A <em>better separation of concerns</em> is created since you are gonna create several <em>Stores</em> for several resources, having the possibility to include specific requirements in each of them. Eg: we could have <em>Stores</em> with different scopes — Singleton vs Screen.</li><li><em>Initial state.</em> A <em>BehaviorSubject</em> supports a default initial value, which can be really useful in different scenarios.</li><li><em>Increased code traceability</em>. Since we are having different Stores, it is clear who and under which conditions the Store is updated.</li></ul><p>The implementation looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f77e6504e6daba11165d484bd98cf98/href">https://medium.com/media/3f77e6504e6daba11165d484bd98cf98/href</a></iframe><blockquote>Implementation Note 1: Exposing the <em>Subject</em>. We mask the <em>Subject</em> by calling <em>.asObservable()</em> method, which will return the <em>Subject</em> as a pure <em>Observable </em>without exposing its <em>Subscriber</em> interface.</blockquote><blockquote>Implementation Note 2: We use <em>.distinctUntilChanged() </em>so we avoid notifying twice the same state.</blockquote><h4>A practical example: Shopping Cart</h4><p>I have built an small demo application to illustrate the concept. The app is a simulation of a <em>Grocery-Store. </em>Within the app<em> </em>we are gonna use our <em>Store</em> concept for sharing the Cart resource across the application. Full source code can be found in the following <a href="https://github.com/czyrux/GroceryStore">Github repo</a>.</p><p>The application contains two main screens: a Catalog and a Cart screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4J6DLquwImcannV9ERRrbg.png" /></figure><p>The idea is that every time we add/remove a product from the Cart, the <em>Cart-Screen</em> and the <em>Cart-Tab-Counter</em> would be updated.</p><p>For this we are gonna create our <a href="https://github.com/czyrux/GroceryStore/blob/master/app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java"><em>CartStore</em></a> object, which extends the previously introduced <em>Store</em> class. We do this to ease injection and code readability.</p><pre>public class CartStore extends Store&lt;Cart&gt; { }</pre><p>Then, in our UI, our components will subscribe to the <em>CartStore</em> in order to get updates. Here is how the <a href="https://github.com/czyrux/GroceryStore/blob/master/app/src/main/java/de/czyrux/store/ui/GroceryStoreActivity.java#L78"><em>Cart-Tab-Counter</em></a> implementation may looked like:</p><pre>cartStore.observe()<br>        .subscribeOn(Schedulers.computation())<br>        .map(cart -&gt; {<br>            int cartProductsCount = 0;<br>            for (CartProduct product : cart.products) {<br>                cartProductsCount += product.quantity;<br>            }<br>            return cartProductsCount;<br>        })<br>        .observeOn(AndroidSchedulers.<em>mainThread</em>())<br>        .subscribe(count -&gt; updateTabTitle(count))</pre><blockquote>As we can see, this subscriber listens for Cart updates, collects the product count within the Cart and then updates the title.</blockquote><p>Finally, we need to make sure that our <em>CartStore</em> gets updated every time that we modify the <em>Cart</em> content. Lets take a look how the <a href="https://github.com/czyrux/GroceryStore/blob/master/app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java">CartService</a> may look for the addToCart operation:</p><pre>public class CartService {<br><br>    private final CartDataSource cartDataSource;<br>    private final CartStore cartStore;<br><br>    // Constructor &amp; others...<br><br>    public Observable&lt;Cart&gt; addProduct(CartProduct cartProduct) {<br>        return cartDataSource.addProduct(cartProduct)<br>                .doOnNext(cart -&gt; cartStore.publish(cart));<br>    }<br>}</pre><pre>public interface CartDataSource {<br>    Observable&lt;Cart&gt; addProduct(CartProduct cartProduct);<br>}</pre><p>As we can see, the <em>CartService</em> talks to the <em>CartDataSource</em> and once the data is updated, it publishes the new content on the <em>CartStore, </em>making it available to other subscribers. This creates a single point of change, which is easier to test and reason about.</p><p>The overall process can be visualized in the following schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Imisgfm2hfWB2TvW3P3HqQ.png" /></figure><h3>Ok… so should I use the Store for everything?</h3><p>Well my recommendation would be to use the <strong><em>Store for the most important resources </em></strong>in your application, like a shopping-cart, favorite-list, user status or similar, but <strong><em>still keep the Bus </em></strong>in case you need to propagate lesser important events.</p><blockquote>Use Store for your more important resources, but still keep the Bus for smaller events if needed.</blockquote><h3>Conclusion</h3><p>In this post we cover the problem that may arise using standard Event Buses for sharing state and how RxJava Subjects can provide a better solution to this problem. We also cover two different solutions to the same problem and the use cases for each of them.</p><p>I hope you enjoy this approach. Feel free to contribute and share your thoughts in the comments.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81db49a0dd8e" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/state-propagation-in-android-with-rxjava-subjects-81db49a0dd8e">State propagation in Android with RxJava Subjects</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[Presenter surviving orientation changes with Loaders]]></title>
            <link>https://medium.com/@czyrux/presenter-surviving-orientation-changes-with-loaders-6da6d86ffbbf?source=rss-ba532f5866b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6da6d86ffbbf</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[Antonio Gutierrez]]></dc:creator>
            <pubDate>Sat, 05 Mar 2016 19:42:04 GMT</pubDate>
            <atom:updated>2016-10-02T14:23:36.673Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP</a> (<em>Model View Presenter</em>) is a trending topic in the Android community nowadays. This pattern allows you to avoid the <em>God</em> Activity/Fragment syndrome, better decoupling and improve testability in your applications.</p><p>You can find many posts with really good explanations about how to apply such pattern in Android applications: <a href="http://antonioleiva.com/mvp-android/">post1</a>, <a href="http://engineering.remind.com/android-code-that-scales/">post2</a> and <a href="http://hannesdorfmann.com/android/mosby">post3</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*33e_JFV1EdHmseiiCrq_-Q.png" /><figcaption>MVP diagram</figcaption></figure><p>The basic idea behind the pattern is to make your Activity/Fragment become a <a href="http://martinfowler.com/eaaDev/PassiveScreen.html"><em>Passive View</em></a> that display given data and delegates all events to a middle man, the <em>Presenter</em> object. The <em>Presenter</em> will decide what to do for every incoming event, retrieving or updating data from the <em>Model</em> and preparing the data so the <em>View</em> can display it. The interaction with the <em>View</em>, in our case the Activity/Fragment, will be done indirectly via an interface that the Activity/Fragment will implement.</p><p>This improve the separation of concerns in presentation logic and facilitate automated testing since this <em>Presenter</em> will not have any Android code reference.</p><h3>The issue with Presenters and configuration changes</h3><p>Most of the developers agree on the core concepts and how to apply them on Android, but there are still some open questions. The one that we are going to talk today is what to do with the <em>Presenter</em> object when a configuration changes occurs. There are a few approaches:</p><h4><em>Let the Presenter be destroyed</em>.</h4><p>In this approach the Presenter will die when the Activity/Fragment dies. If we wanna restore some state we would need to make use of <strong><em>onSaveInstanceState</em></strong><em>, </em>via being the <em>View</em> the one that saves this data and then provide it to the Presenter upon creation<em>, </em>or giving the Presenter a chance to store some data by himself passing the save instance <em>Bundle</em>. While this approach can work with some simple data, it will get more complicated if what we want to keep is the reference to some ongoing background operation.</p><h4><em>Keep the Presenter somewhere</em> and restore once the component is recreated.</h4><p>This idea is the one that I have seen the most. However, implementations can differ quite a bit between each other.</p><p>The easiest one, and a bit naive, would be to store the Presenter in a <strong><em>static reference </em></strong>within the Activity/Fragment. This approach will allow us to keep the Presenter instance across orientation changes but will limit the amount of living instances of the combination “<em>Presenter — Activity/Fragment</em>” to only one in the entire application. Imaging what would happen in a situation when we have multiple instances of the same Fragment in a ViewPager… <em>ups!</em></p><p>Another solution could be to use<strong> <em>Fragment </em></strong><a href="http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)"><strong><em>setRetainInstance(true)</em></strong></a><em>.</em> Setting this property in a Fragment will certainly make that Fragment not be destroyed, giving us the change to survive the Presenter altogether. However this is not a complete solution since we cannot use it with <em>child fragments </em>and<em> it is not available for Activities</em>.</p><p>The final alternative that I have seen would be to use a <strong><em>singleton cache</em></strong> <strong><em>with some kind of identifiers</em></strong> to store different instances of the same Presenter. In order to preserve this identifier on configuration change the Activity/Fragment should make use of <em>onSaveInstanceState</em>. The issue here is <em>when to remove</em> the Presenter from the singleton cache plus all the additional logic that needs to be handled.</p><h4>A new approach</h4><p>As we can see, all the approaches have some caveats or corner cases that make them tricky to get right. After give some more thought and being inspired by this nice blog post about Loaders: <a href="https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832#.c76yd3ent"><em>Making loading data lifecycle aware</em></a>, I would like to introduce a new approach:<strong> use <em>Loaders</em> to preserve <em>Presenters</em> during rotation</strong>.</p><h3>But first… what are Loaders and what they give to us?</h3><blockquote>For an in deep explanation about how Loaders work please refer to official <a href="https://developer.android.com/intl/es/guide/components/loaders.html">documentation</a> or this nice series of blog <a href="http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html">posts</a> by<a href="https://plus.google.com/+AlexLockwood"> Alex Lockwood</a>.</blockquote><p>As we all know, by default, <a href="http://developer.android.com/guide/topics/resources/runtime-changes.html">device configuration changes</a> such as rotating your screen involve restarting your whole <em>Activity</em>. <a href="http://developer.android.com/reference/android/content/Loader.html"><em>Loaders</em></a> are a tool provided by the Android framework that<strong> survive configuration changes</strong>. Their lifecycle will be managed by the system and they will be automatically cleaned up when the requesting Activity or Fragment is permanently destroyed. That means <em>no additional logic on the application side to decide when to delete them</em>.</p><p>Originally Loaders <em>main use case</em> is to load some data in background, via extending <a href="http://developer.android.com/reference/android/content/AsyncTaskLoader.html">AsyncTaskLoader</a> and <a href="http://developer.android.com/reference/android/content/CursorLoader.html">CursorLoader</a>, specially shining with this one, a content provider and a SQLite database. But as the previous mentioned <a href="https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832#.clns3tg8c">post</a> stands, they could also be used without a background thread via extending the base Loader directly.</p><h3>Thats great, but… what does it have to do with Presenters?</h3><p>Well, as we already mention, the problem with <em>Presenters</em> is where to store them and when to decide that their time is over. On the other hand, we just saw a few capabilities about <em>Loaders</em>: they are a tool provided by the framework that is lifecycle aware, the system will take care of cleaning them up when their time has come to an end and last but not least, they don’t necessary need to run in background.</p><p>So considering our needs and the Loader capabilities, we can use <em>Loaders</em> as a provider for our <em>Presenter</em> instances without worrying about configuration changes.</p><blockquote>“<em>use a synchronous Loader as a cache</em> to store our Presenter”</blockquote><p>The catch here is that by using the Loader <em>synchronously</em> we can be sure at which moment during the <em>lifecycle</em>* the Presenter will be initialized and ready to interact. All before the Activity/Fragment is visible to the user.</p><blockquote><strong>*Note</strong>: There is a important difference in regard to when Presenter will be delivered to Activities or Fragments. In Activities, after calling <strong>super.onStart</strong> the Presenter will be ready to use in every circumstance. However, in Fragments when first created, the Presenter will be deliver after super.onStart, but on recreation it will be delivered after super.onResume. So, on Fragments we can just rely that our Presenter will be there after <strong>super</strong>.<strong>onResume.</strong></blockquote><p>Other key <em>Loader</em> feature that make this whole idea work is how are they managed by the system. Each instance of Fragment/Activity will have their own <a href="http://developer.android.com/reference/android/app/LoaderManager.html"><em>LoaderManager</em></a>, which will control the <em>Loaders</em> associated with <em>this and only this</em> specific Android component, making possible to have two instances of the same Android component with their corresponding <em>Loader</em> alive at the same time.</p><h3>Ok ok, that sounds nice, so how we translate that to code?</h3><p>First we should create our Loader implementation extending directly the <a href="https://developer.android.com/intl/es/reference/android/content/Loader.html">Loader</a> class. Take into account that we wont subclass <a href="https://developer.android.com/intl/es/reference/android/content/CursorLoader.html">CursorLoader</a> or <a href="https://developer.android.com/intl/es/reference/android/content/AsyncTaskLoader.html">AsyncTaskLoader</a> since we do not want the background capabilities that they provide. The implementation could looks as follows:</p><pre>public class PresenterLoader&lt;T extends Presenter&gt; extends Loader&lt;T&gt;{<br><br>    private final PresenterFactory&lt;T&gt; factory;<br>    private T presenter;<br><br>    // Constructor...<br><br>    @Override<br>    protected void onStartLoading() {<br><br>        // If we already own an instance, simply deliver it.<br>        if (presenter != null) {<br>            deliverResult(presenter);<br>            return;<br>        }<br><br>        // Otherwise, force a load<br>        forceLoad();<br>    }<br><br>    @Override<br>    protected void onForceLoad() {<br>        // Create the Presenter using the Factory<br>        presenter = factory.create();<br><br>        // Deliver the result<br>        deliverResult(presenter);<br>    }<br><br>    @Override<br>    protected void onReset() {<br>        presenter.onDestroyed();<br>        presenter = null;<br>    }<br>}</pre><p>In this implementation <em>Presenters</em> should implement an interface that could look like:</p><pre>public interface Presenter&lt;V&gt;{<br>    void onViewAttached(V view);<br>    void onViewDetached();<br>    void onDestroyed();<br>}</pre><p>The key elements in here are:</p><ul><li><em>onStartLoading()</em>: Will be called by the Framework for a <em>new or already created</em> Loader once Activity <em>onStart()</em> is reached. In here we check whether we hold a Presenter instance (— in which situation it will be delivered immediately) or the Presenter needs to be created.</li><li><em>onForceLoad()</em>: Called when <em>forceLoad()</em> is invoked. Here we are calling the Factory to create our Presenter and delivering the result.</li><li><em>deliverResult(): </em>will deliver our Presenter to the Activity/Fragment.</li><li><em>onReset()</em>: will be call before the Loader gets destroyed, giving us the chance to communicate this to the Presenter in case some ongoing operation could be cancelled or additional clean ups would be required.</li><li><em>PresenterFactory</em>: this interface will hide the details about how to create a Presenter when is required. We use this approach to favour composition over inheritance so we avoid the need of subclassing this PresenterLoader class to provide different Presenters. This interface could look as simple as:</li></ul><pre>public interface PresenterFactory&lt;T extends Presenter&gt; {<br>    T create();<br>}</pre><h4>So how would it look from the Activity/Fragment point of view?</h4><p>Ok, so now that we have our Loader implementation in place, we need to connects our activities and fragments. The connection point will be the <a href="http://developer.android.com/reference/android/support/v4/app/LoaderManager.html"><strong><em>LoaderManager</em></strong></a>. We will call <em>FragmentActivity</em>’s <em>getSupportLoaderManager()</em> or <em>Fragment</em>’s <em>getLoaderManager()</em> to get our instance and then call <a href="http://developer.android.com/reference/android/support/v4/app/LoaderManager.html#initLoader(int,%20android.os.Bundle,%20android.support.v4.app.LoaderManager.LoaderCallbacks%3CD%3E)"><strong><em>initLoader()</em></strong></a><strong>. </strong>Google recommends calling this method in<strong> Activity#<em>onCreate()</em> or Fragment#<em>onActivityCreated().</em></strong></p><blockquote>When calling <em>initLoader</em> we pass<strong><em> </em></strong>a unique id (unique within that <em>Activity</em>/<em>Fragment </em>— not globally unique) to identify the <em>Loader</em>, an optional Bundle — which in this case won’t be need, and an instance of <a href="http://developer.android.com/reference/android/support/v4/app/LoaderManager.LoaderCallbacks.html"><em>LoaderCallbacks</em></a>.</blockquote><blockquote>Note: As pointed out in the previous linked <a href="https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832#.2pi1bukv1">blog post</a> <strong>do not call <em>initLoader()</em> within a Fragment’s <em>onCreate()</em></strong> — always wait for <em>onActivityCreated()</em> or you’ll run into issues where Loaders appear to be shared across fragments as noted in <a href="https://code.google.com/p/android/issues/detail?id=94081">this Lint request</a> and <a href="https://plus.google.com/+JonFHancock/posts/bgXh4XEAeui">this related Google+ post</a>.</blockquote><blockquote>Note 2: <strong>(UPDATE: Following issue has been fix in Support Library 24.x.x onwards)</strong>. Following this recommendation yields the following problem : <strong>onLoadFinished will be called twice during configuration changes. </strong>The situation is explained clearly in this <a href="https://stackoverflow.com/questions/15515799/should-we-really-call-getloadermanager-initloader-in-onactivitycreated-which#">stackoverflow pos</a>t. Depending on what we do with the Presenter after being delivered it that can become an issue. In such case a possible workaround is calling initLoader in Fragment’s onResume. Another solution would be to keep the call in onActivityCreated and have some internal flag so we avoid delivering twice — You can check the latest solution in the <a href="https://github.com/czyrux/MvpLoaderSample/blob/master/app/src/main/java/de/czyrux/mvploadersample/base/BasePresenterFragment.java">linked code</a>.</blockquote><p>This call to <em>initLoader</em> will hook ourselves in the component lifecycle, receiving a call <em>onStartLoading()</em> when <em>onStart()</em> method is call and <em>onStopLoading()</em> when <em>onStop()</em>. However, <em>onReset()</em> will only be called if the Loader is destroy due to the Activity/Fragment being destroyed or because <a href="http://developer.android.com/reference/android/app/LoaderManager.html#destroyLoader(int)"><em>destroyLoader</em></a><em>() </em>has been<em> </em>called.</p><p>The <em>LoaderManager</em><strong><em> </em></strong>includes a <a href="http://developer.android.com/reference/android/support/v4/app/LoaderManager.html#restartLoader(int,%20android.os.Bundle,%20android.support.v4.app.LoaderManager.LoaderCallbacks%3CD%3E)"><em>restartLoader()</em></a><em> </em>method which gives you the ability to force a reload. In our case it would not be necessary unless for some reason we wanted to manually recreate our Presenter.</p><h4>But how do I get my Presenter? LoaderCallbacks</h4><p><em>LoaderCallbacks</em> is the communication point between Activity/Fragment and the Loader. There are three callbacks:</p><ul><li><em>onCreateLoader()</em> — where you construct the actual Loader instance.</li><li><strong><em>onLoadFinished()</em> — where Loader will deliver its work, the Presenter in our case.</strong></li><li><em>onLoaderReset()</em> — your chance to clean up any references to the data.</li></ul><h4>Show me the code</h4><pre>public class SampleActivity extends AppCompatActivity implements SomeView, LoaderManager.LoaderCallbacks&lt;Presenter&gt; {<br><br>    private static final int <em>LOADER_ID </em>= 101;<br>    private Presenter presenter;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br><br>        // initialization code...<br><br>        <strong>getSupportLoaderManager().initLoader(<em>LOADER_ID</em>, null, this);</strong><br>    }<br><br>    @Override<br>    protected void onStart() {<br>        super.onStart();<br><br>        // Ready to use presenter<strong><br></strong>        <strong>presenter.onViewAttached(this);</strong><br>    }<br><br>    @Override<br>    protected void onStop() {<br>        <strong>presenter.onViewDetached();<br></strong>        super.onStop();<br>    }<br><br>    // Some other activity code and view interface implementation...<br><br><br>    @Override<br>    public Loader&lt;Presenter&gt; onCreateLoader(int id, Bundle arg){<br>        return new PresenterLoader&lt;&gt;(this, new SomeFactoryImpl());<br>    }<br><br>    @Override<br>    public void onLoadFinished(Loader&lt;Presenter&gt; loader, Presenter presenter) {<br>        <strong>this.presenter = presenter;</strong><br>    }<br><br>    @Override<br>    public void onLoaderReset(Loader&lt;Presenter&gt; loader) {<br>        presenter = null;<br>    }<br>}</pre><p>The key elements in here are:</p><ul><li>Init <em>Loader</em> with a unique ID within this instance of Activity/Fragment.</li></ul><pre>getSupportLoaderManager().initLoader(<em>LOADER_ID</em>, null, this);</pre><ul><li>Calling <em>super.onStart</em> will create or reconnect to an existing <em>Loader</em> and <em>onStartLoading</em> will be called. In our case this will create or deliver the <em>Presenter</em> instance in <em>onLoadFinished.</em> All of this will happen on the<em> main UI thread</em>, so by the time <em>super.onStart</em> is finished our Presenter will be ready to be used.</li><li>If the <em>Loader</em> needs to be created, the system will call <em>onCreateLoader</em>, where we will create our instance passing the proper <em>PresenterFactory </em>implementation<em>.</em></li></ul><pre>    @Override<br>    public Loader&lt;Presenter&gt; onCreateLoader(int id, Bundle arg){<br>        return new PresenterLoader&lt;&gt;(this, new SomeFactoryImpl());<br>    }</pre><h3><em>Et voila!</em></h3><p>So summarizing a bit, we have seen that <em>Loaders</em> are a tool provided by the Android framework that offers the following:</p><ul><li>They will be kept during <em>configuration changes</em>.</li><li>They are <em>cleaned up by the system</em> when the Activity/Fragment is no longer needed.</li><li>They are tied to the Activity/Fragment lifecycle, so this events could be propagated.</li><li>Each Activity/Fragment will have attached their own <em>Loader</em> instances, so several combination of “Presenter-Activity/Fragment” can be <em>living</em> <em>at</em> <em>the same time, </em>as in a ViewPager<em>.</em></li><li>Loaders can run <em>synchronously</em>, making deterministic when its content will be deliver and ready to use.</li></ul><p>So putting all this together and creating the proper abstractions, we have a good tool to “cache” our <em>Presenters</em> during orientation changes, making them survive as long as it is required.</p><p>You can check a <a href="https://github.com/czyrux/MvpLoaderSample">sample project</a> using this approach in different scenarios <em>(MVP in an Activity, a Fragment or Fragment within a ViewPager) </em>and the main constructs used during this post in this <a href="https://gist.github.com/czyrux/f2eff89628b6309761d9">gist</a>.</p><p>I would like to hear your thoughts in this approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6da6d86ffbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>