<?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 Frederico Sabino on Medium]]></title>
        <description><![CDATA[Stories by Frederico Sabino on Medium]]></description>
        <link>https://medium.com/@fmrsabino?source=rss-6b1323a825b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RGW30uNaTB_uGTjOQEj7Jg.jpeg</url>
            <title>Stories by Frederico Sabino on Medium</title>
            <link>https://medium.com/@fmrsabino?source=rss-6b1323a825b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:14:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fmrsabino/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[An approach to MVP/MVI using RxJava 2 & Dagger 2 (Part 2 of 2— One chain of events)]]></title>
            <link>https://medium.com/@fmrsabino/an-approach-to-mvp-mvi-rxjava-2-dagger-2-part-2-of-2-one-chain-of-events-33e171096436?source=rss-6b1323a825b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/33e171096436</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Frederico Sabino]]></dc:creator>
            <pubDate>Sat, 27 May 2017 18:22:21 GMT</pubDate>
            <atom:updated>2017-05-28T21:41:38.000Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@fmrsabino/an-approach-to-mvp-mvi-with-dagger-2-part-1-viewmodel-is-here-bdfc09c8732">Part 1</a> I’ve mentioned some of the solutions which allow the survival of components in configuration changes. Google IO 2017 introduced an easy way to handle that problem with ViewModels. I’ve decided to update one of my old MVP projects with one goal in mind: having one simple flow of events from and to the UI.</p><h4>What were the issues with my previous MVP solution?</h4><p>Looking back at the project I can conclude that it has 2 main issues:</p><ol><li><strong>I broke the chain of events.</strong> My presenters listened to events in the stream and notified the view. Since the view is a component that could be destroyed and recreated while the presenter survived, I had yet another flow to bridge that gap. I’ve used Subjects (from RxJava) and Relays (from RxRelay).</li><li><strong>Events arrived from multiple sources.</strong> The way I closed the gap was with multiple bridges. One bridge for the loading of data, one for the data, one for the errors in the stream. The problem with this solution is that the view needs to keep track of what is the current state from multiple sources (regarding network requests, data loading, etc…).</li></ol><p>These problems are explained in greater detail in <a href="http://hannesdorfmann.com/android/mosby3-mvi-1">this article series from Hannes Dorfmann</a>.</p><h3>Current solution</h3><p>My current solution has 3 main components for the UI/Presenter part:</p><ul><li><strong>Activity/Fragment</strong> — The View part from MVP</li><li><strong>Presenter</strong> — holds the business logic and communicates with the rest of the app components (extends ViewModel).</li><li><strong>Contract interface</strong> — it serves as the communication interface between the View and Presenter</li></ul><p>We already have a presenter that survives configuration changes. But we still need to simplify the flow of events. The View produces UI events (clicks, pull to refresh, swipes, etc…) and consumes the results of these actions. In order to have one single source of events we are going to create an abstraction for the UI. Let’s call it UIModel. This UIModel is a simple container holding the necessary data for the view to display (collections, error messages, loading status). It allows two things:</p><ol><li>Given a specific UIModel we have a specific representation for it. Since these UIModels are produced by the respective Presenters we can abstract the Presenter and produce a series of UIModels in order to test how the UI renders each state.</li><li>We can now have one single stream with the representation of the UI state. That means that the Activity/Fragment sends <strong>upstream</strong> a series of UI events and the <strong>downstream</strong> represents a sequence of UIModels to be rendered.</li></ol><p>This upstream/downstream concept is something that can be represented by an ObservableTransformer&lt;Upstream, Downstream&gt; and it’s this concept that will help us construct a single chain of events. More on the topic can be found on this <a href="http://blog.danlew.net/2015/03/02/dont-break-the-chain/">article by Dan Lew</a>.</p><h4>Designing the single stream</h4><p>To merge the UIEvents on a single stream we can use the .merge() operator from Rx. Having reactive streams associated with the view events is really helpful and for that I recommend using <a href="https://github.com/JakeWharton/RxBinding">RxBinding</a>. You can also use Subjects to emit those events.</p><pre>val uiEvents: Observable&lt;UiEvent&gt; = Observable.merge(<br>   login.clicks().map{ LoginClick() }, <br>   forgotPassword.clicks().map { ForgotPasswordClick() }, ...)</pre><p>As you might have noticed I’m mapping these events clicks to a representation of those actions. These representations implement an UiEvent interface (which can be empty). They are simply representations of the each UIEvent that you want to handle.</p><p>Now how can we handle each distinct UIEvent? We can use the .publish() operator in order to check the type of each event.</p><pre>uiEvents.publish { events -&gt;<br>   when(events) {<br>       is LoginClick -&gt; handleLoginClickEvents(events)<br>       is ForgotPasswordClick -&gt; handleForgotPwClickEvents(events)<br>}</pre><p>But we want to merge the results produced by handleLoginClickEvents and handleForgotPwClickEvents back to a single stream. We can use again the .merge() operator to achieve that!</p><p>In addition we can use a combination of the .ofType() operator in order to get rid of the explicit cast with the when block.</p><pre>uiEvents.publish { events -&gt;<br>    Observable.merge(<br>        events.ofType(LoginClick::class.java).flatMap { ... },<br>        events.ofType(ForgotPasswordClick::class.java).flatMap {...}    <br>}</pre><p>We can now extract the .publish() to its own ObservableTransformer . We can even call .compose() for each type of event. It’s like creating a new operator and extracting it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bab21b8c41b4b20407c848663913fde/href">https://medium.com/media/6bab21b8c41b4b20407c848663913fde/href</a></iframe><p>Let’s see what is happening when the stream receives a Login click event:</p><ol><li>It is matched up with the correct transformer through the .ofType() operator. Since it is a LoginClick it is going to be handled by the LoginTransformer</li><li>When the LoginTransformer receives the event we immediately send an event to the stream with .startWith() . This event represents that a request is in flight.</li><li>For each LoginClick event we are going to call .getAccount() on the repository. If we get a result we map it to a representation of that result. If we get an error we map to a representation of that error.</li></ol><p>But there’s actually an issue with the code above. The transformer receives UiEvent and produces MainActivityUiModel which is not what the loginTransformer is doing!</p><p>I actually missed one line in the transformer :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec79b2126de6fcb49d63159cb1b8f881/href">https://medium.com/media/ec79b2126de6fcb49d63159cb1b8f881/href</a></iframe><p>The .scan() operator allows to have an initial state and produce a new state with the changes produced by the other Transformers. I start with the default MainActivityUiModel which represents the UI as it is initially shown (ie.: no network calls/no data loaded). For each result that we receive (produced by the transformers) we apply it to the current UI state using the stateReducer function. The stateReducer will simply check what’s the result and modify the UI state accordingly. Thus we get what we wanted: UI events <strong>upstream</strong>, UI models <strong>downstream</strong>.</p><h3>How it all fits together with MVP/MVI</h3><p>If you remember correctly, our uiEvents was an Observable.merge() of all the events that occurred in the Activity/Fragment so it must have been on the Activity/Fragment side right?</p><p>Yes it was, but we need to save that Observable in a layer that survives configuration changes or we will be back to the original problem of cancelling network calls or other background tasks associated with that Observable. So instead of having that Observable.merge() on the UI side we move it to the Presenter but we also change it to a Subject — we can’t have the same Observable.merge() on the Presenter side because we don’t have access to the views (and rightfully so)!</p><h4>So again… What is in the Presenter?</h4><p>The presenter has the following important components:</p><ul><li>All the ObservableTransformer logic</li><li>The Subject&lt;UIEvent&gt; that the UI connects to in order to send UIEvent</li><li>An Observable&lt;UIModel&gt; exposed to the Activity/Fragment</li></ul><p>The Subject&lt;UIEvent&gt; can just be something like this:</p><pre>val uiEvents: PublishSubject&lt;UiEvent&gt; = PublishSubject.create&lt;UiEvent&gt;()</pre><p>The Observable&lt;UIModel&gt; takes the events going through that Subject and composes it with our Transformer logic.</p><pre>val uiModelObservable: Observable&lt;MainActivityUiModel&gt; = uiEvents.compose(transformer).replay(1).autoConnect()</pre><p>You might ask: Since we subscribing and unsubscribing from the View which can be destroyed don’t we have the same problem of cancelling ongoing tasks? That’s where .replay(1).autoConnect() comes into play. You can think of .replay() as an Rx caching mechanism with a buffer size of 1. .autoConnect() converts it to an Observable.</p><p>Remember that since presenters extends ViewModel they are going to survive configuration changes of the device. When the view is recreated again, it simply starts observing the stream provided by the presenter (by subscribing to the uiModelObservable) which is going to have the state before the configuration change.</p><h4>What about the Activity/Fragment?</h4><p>On the view side we only have access to what the Contract interface exposes:</p><ul><li>An Observable&lt;UIModel&gt;</li><li>A Subject&lt;UIEvent&gt;</li></ul><p>And that’s all we need for the View side. We can now:</p><ol><li>Retrieve the presenter through the ViewModel framework (explained in <a href="https://medium.com/@fmrsabino/an-approach-to-mvp-mvi-with-dagger-2-part-1-viewmodel-is-here-bdfc09c8732">Part 1</a>).</li><li>Send UIEvent to the presenter: presenter.uiEvents.onNext(UIEvent)</li><li>Receive UIModel by subscribing to the observable exposed by the presenter: presenter.observeUIModel().subscribe() (don’t forget to call .dispose()).</li></ol><p>What you do with each UIModel is completely up to you. It just needs to have all the information needed to update your view.</p><h3>Conclusion</h3><p>This architecture and data flow solve the “multiple sources” problem and it clearly separates the responsibility for each component. The View sends UI events and receives a representation of the current UI state. The Presenter receives the UI events, does the business logic around them and produces a UI model for the view to render. Additionally we can easily test each component: we can abstract the View and produce a series of UIEvents to consume by the Presenter (with unit tests) and we can also see how the view is rendered given different UIModels.</p><p>One thing that might be confusing is having both UIModel (our view state) and ViewModel (our presenter) but, naming issues aside, I consider this solution easy to read and robust. Certainly easier than having our own logic to handle configuration changes or adding an additional component lifecycle to handle it.</p><p>This was largely inspired by <a href="http://hannesdorfmann.com/android/mosby3-mvi-1">Hannes Dorfmann’s article series</a> and Jake Wharton’s presentation on Managing State which you can watch below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0IKHxjkgop4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0IKHxjkgop4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0IKHxjkgop4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed64671ece0c6f745c71086f43dd21ff/href">https://medium.com/media/ed64671ece0c6f745c71086f43dd21ff/href</a></iframe><p>I appreciate any given feedback and any improvements to this solution. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33e171096436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An approach to MVP/MVI using RxJava 2 & Dagger 2 (Part 1 of 2 — ViewModel is here)]]></title>
            <link>https://medium.com/@fmrsabino/an-approach-to-mvp-mvi-with-dagger-2-part-1-viewmodel-is-here-bdfc09c8732?source=rss-6b1323a825b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdfc09c8732</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Frederico Sabino]]></dc:creator>
            <pubDate>Sat, 27 May 2017 15:04:34 GMT</pubDate>
            <atom:updated>2017-05-27T20:56:32.763Z</atom:updated>
            <content:encoded><![CDATA[<p>Throughout the years that I’ve been developing and reviewing Android applications, most of them had problems dealing with configuration changes: the application makes a network request/computation task and if the device rotates it’s all gone and we need to restart those tasks.</p><h4>Pre-ViewModel solutions</h4><p>While some applications simply don’t allow configuration changes, others try to solve it in different ways:</p><ul><li>Singleton pattern/Component living on a higher scope which keeps track of these events</li><li>Fragment.setRetainInstance(boolean)</li><li>Using <a href="https://developer.android.com/reference/android/support/v4/content/Loader.html">Loaders</a></li></ul><p>These were the most common patterns that I’ve seen to solve this problem. One that worked really well for me was using Loaders. They survive configuration changes so any data that they hold also survives. This might include Presenters/Controllers/anything really. To know more how you can implement a component that survives configuration changes I recommend reading <a href="https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832">this great article</a> by Ian Lake.</p><p>So we already have the problem solved why bother? Well there are some keypoints that you need to be aware before starting using Loaders:</p><ol><li>They involve quite some boilerplate to set them up. Well maybe not that much but we need to consider the lifecycle of the Loader itself (on top of the Activity/Fragment lifecycle)</li></ol><pre>class PresenterLoader&lt;T : BasePresenter&lt;*&gt;&gt;(context: Context, private val creator: () -&gt; T) : Loader&lt;T&gt;(context) {<br>    private var presenter: T? = null<br><br>    override fun onStartLoading() {<br>        presenter?.<em>let </em><strong>{ </strong>deliverResult(presenter); return <strong>}<br>        </strong>forceLoad()<br>    }<br><br>    override fun onForceLoad() {<br>        presenter = creator()<br>        deliverResult(presenter)<br>    }<br><br>    override fun onReset() {<br>        presenter?.onDestroyed()<br>        presenter = null<br>    }<br>}</pre><p>2. They are attached to the Activity/Fragment lifecycle but in a restrictive way. As Ian Lake mentions in the article:</p><blockquote>In almost every case, there’s only one method you’ll need to call: <a href="http://developer.android.com/reference/android/support/v4/app/LoaderManager.html?utm_campaign=adp_series_loaders_020216&amp;utm_source=medium&amp;utm_medium=blog#initLoader(int,%20android.os.Bundle,%20android.support.v4.app.LoaderManager.LoaderCallbacks&lt;D&gt;)"><strong><em>initLoader()</em></strong></a><strong>. This is generally called in </strong><a href="http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html?utm_campaign=adp_series_loaders_020216&amp;utm_source=medium&amp;utm_medium=blog#onCreate(android.os.Bundle)"><strong><em>onCreate()</em></strong></a><strong> or </strong><a href="http://developer.android.com/reference/android/support/v4/app/Fragment.html?utm_campaign=adp_series_loaders_020216&amp;utm_source=medium&amp;utm_medium=blog#onActivityCreated(android.os.Bundle)"><strong><em>onActivityCreated()</em></strong></a></blockquote><p>Given this, Loaders are a great option to store components that survive configuration changes but they also come with the drawbacks of dealing with an additional lifecycle and the knowledge on how it attaches to the current Activity/Fragment/View lifecycle.</p><h3>ViewModel — a solution using Dagger 2</h3><p>Google announced at IO 2017 a new set of libraries: <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a>. The main goal of these components is to help design a better application.</p><p>One of those components is the ViewModel.</p><blockquote>The <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html">ViewModel</a> class is designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations.</blockquote><p>This image from the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html">ViewModel webpage</a> shows that the ViewModel scope survives configuration changes which is what we wanted to achieve with the Loaders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*3Kr2-5HE0TLZ4eqq8UQCkQ.png" /></figure><p>Moreover, it is really simple to use! You just need to extend ViewModel on the component that you want to persist. Then you can obtain that instance in your Activity/Fragment:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    presenter =      ViewModelProviders.of(this).get(MyPresenter::class.<em>java</em>)<br>}</pre><p>Now you might have noticed that we are not directly using the constructor to get MyPresenter . What about Dependency Injection? There are two ways to accomplish this with Dagger 2 and ViewModels:</p><ol><li>Instead of extending ViewModel you can extend AndroidViewModel(Application) instead and then you can have an initialization block to inject the dependencies:</li></ol><pre>class MyPresenter(application: Application) : AndroidViewModel(application){<br>    @Inject lateinit var repository: MyRepository<br>    init {<br>       (application as Application).component.inject(this)<br>    }<br>}</pre><p>2. Create a ViewModelProvider.Factory which can be injected:</p><pre>class MyPresenter(repository: MyRepository) : ViewModel() { ... }</pre><pre>@ForView //Dagger 2 Scope<br>class Factory @Inject constructor(val repository: MyRepository) : ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;?): T {<br>        @Suppress(&quot;UNCHECKED_CAST&quot;)<br>        return MyPresenter(repository) as T //ugly I know<br>    }<br>}</pre><p>and in the Activity I can inject this Factory and call</p><pre>@Inject lateinit var factory: Factory</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    inject()    <br>    presenter = ViewModelProviders.of(this,factory).get(MyPresenter::class.<em>java</em>)<br>}</pre><p>The first solution is simpler and you don’t have to create a Factory ! The problem here is that we are now requesting the dependencies in the init block instead of having them injected in the constructor. You will also need to mock the Application class if you want to test this component which is not ideal.</p><p>That’s why I prefer the second one. Yes… I have to create a Factory for it and you have the ugly cast but it’s easier to see the dependencies which are being injected and, when writing tests, I can mock my own class.</p><p>And that’s it. Beware that the ViewModel was just released and at the time of writing it is currently on version 1.0.0-alpha1. In <a href="https://medium.com/@fmrsabino/an-approach-to-mvp-mvi-rxjava-2-dagger-2-part-2-of-2-one-chain-of-events-33e171096436">Part 2</a> I’m going to explain my current approach to MVP/MVI while using ViewModels to survive configuration changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdfc09c8732" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>