<?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 Daniel Tartaglia on Medium]]></title>
        <description><![CDATA[Stories by Daniel Tartaglia on Medium]]></description>
        <link>https://medium.com/@danielt1263?source=rss-656abcc75dfd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QCVqClPoHtUUjQ7r.</url>
            <title>Stories by Daniel Tartaglia on Medium</title>
            <link>https://medium.com/@danielt1263?source=rss-656abcc75dfd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 13 Jul 2026 19:07:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielt1263/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[Idle Thoughts on Technical Debt]]></title>
            <link>https://danielt1263.medium.com/idle-thoughts-on-technical-debt-85b2be26a747?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b2be26a747</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technical-debt]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 01:13:08 GMT</pubDate>
            <atom:updated>2022-08-25T01:13:08.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Technical debt is a term of art that describes code that has outlived its usefulness but hasn’t been removed from the project.</p><p>For example, it can be used to describe code that was written before the requirements were fully understood and is found to be lacking once more information is available. Rather than rewrite the code from scratch (which is likely better in the long term), developers often hack around the substandard code’s limitations (which can be better in the short term.)</p><p>Another form is code that exists to implement a feature that is no longer needed. Disabling a feature generally only requires deleting a single line of code which renders hundereds of other lines obsolete.</p><p>Technical debt is an inevitable part of any evolving software system. There is rarely a business case to remove dead code or rewrite a whole module into a more efficient version, and developers rarely have the patience to do the kind of analysis necessary to remove all debt even when they have the time.</p><p>Too much technical debt makes software hard to update, slowing developers down. However, spending an inordinate amount of time removing the debt will also slow developers down. Therefore, it is something that developers must manage. When adding features to a project, and especially when fixing bugs, developers must allow extra time to remove some of the debt.</p><p>When velocity is high, project managers must prepare themselves for the inevitable complaints of too much debt buildup and should build in a “slow down” period, encouraging developers to attack the debt. When velocity is low, it would be helpful to determine if it’s because of debt buildup. If so, then allow for the velocity to slow even further to give the developers a chance to attack the built up debt.</p><p>Knowing exactly how much debt is acceptable, and what debt is most costly, is not something that the industry has found a way to quantify. To date, developers use subjective feelings about the state of the code rather than any hard metrics on how much is too much, or when too much time is being spent removing debt.</p><p>In my opinion, having general stories with titles like “pay down debt” or “refactor code” are a mistake. It encourages developers to cast around looking to clean up the low hanging fruit. But if a developer is complaining about a particular module being a pain to work with, that’s a good time to create a story to replace that particular module with something that has been better designed. Also, when determining story points, developers should be encouraged to consider if there is any already existing code that the new feature depends on which could use a going over, and bump up the points for the story to give them a chance to do that. This is especially true when it comes to fixing bugs. A bug in the code is a great time to realize that the module containing the bug likely has too much debt and the developer should consider doing more than just making the code work again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b2be26a747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing With Resources in RxSwift]]></title>
            <link>https://danielt1263.medium.com/dealing-with-resources-in-rxswift-cd149d2322f4?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd149d2322f4</guid>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sat, 28 May 2022 22:50:31 GMT</pubDate>
            <atom:updated>2022-06-03T11:52:13.371Z</atom:updated>
            <content:encoded><![CDATA[<p>The Observable.using(_:observableFactory:) function is designed to tie the lifetime of a resource to the subscription of an Observable. In order to use it, you provide a closure that creates the resource and another closure that returns the Observable that will be tied to the resource. Then anytime the Observable returned by using is subscribed to, the operator will call both closures in order to create the resource and return an Observable, bound to the one from the second function. When the Observable is disposed, the using operator will call dispose() on the resource and then deallocate it.</p><h4>Making a Resource</h4><p>All this is pretty abstract though. What does it look like in practice? I recently was working on a screen that played audio files. One way to do that is to use the AVAudioPlayer class; a resource.</p><pre><strong>final</strong> <strong>class</strong> AudioSession: Disposable {<br>    <strong>let</strong> audioPlayer: AVAudioPlayer<br>    <strong>init</strong>(url: URL) <strong>throws</strong> {<br>        audioPlayer = <strong>try</strong> AVAudioPlayer(contentsOf: url)<br>        audioPlayer.play()<br>    }<br>    <strong>func</strong> dispose() {<br>        audioPlayer.stop()<br>    }<br>}</pre><p>When the above resource is created, it will make the audio player and start playing. When the resource is disposed, it will stop the audio player. Now we can use it in the using operator like so:</p><pre><strong>let</strong> session = Observable.using({<br>    <strong>try</strong> AudioSession(url: url)<br>}, <br>observableFactory: { audioSession <strong>in<br>    </strong>Observable&lt;Never&gt;.never()<br>})</pre><p>When you subscribe to session it will create the AudioSession resource, and thus start playing the sound file. When you dispose that subscription, it will stop playing the sound file and delete the audio player object.</p><h4>Getting Information Out of a Resource</h4><p>As written, the above observable doesn’t emit anything. Its only reason for existence is to create and dispose the resource, but it can emit information about the observable. For example, you could have it emit the current play time:</p><pre><strong>return</strong> Observable&lt;Int&gt;.interval(<br>    .milliseconds(100),<br>    scheduler: MainScheduler.instance<br>)<br>.flatMap { _ <strong>in<br>    </strong>Observable.just(audioSession.audioPlayer.currentTime)<br>}</pre><p>Putting the above code into the observableFactory closure will let you know something about what’s going on with the resource. More information can be added as well.</p><h4>Sending Information Into a Resource</h4><p>You can also send information into the resource using an Observable. For example toggling from the play/pause state.</p><p>If you give your resource a dispose bag, you can add yet more to that closure:</p><pre>togglePlay // an Observable&lt;Void&gt;<br>.subscribe(onNext: audioSession.audioPlayer.toggle)<br>.disposed(by: audioSession.disposeBag)</pre><p>(The toggle() function is an extension I wrote to toggle between play and pause.)</p><h4>Other Uses for using</h4><p>So any time you need to create and release resources in your Rx code, the using operator is there to help you. However, it can be used for even more. Anytime you want to call some code during subscription and call other code during dispose, the using operator is your friend.</p><p>One of the most interesting ideas I’ve had for the operator is when I treated a UIViewController as a resource. Resource creation makes the view controller and presents it, and disposing the resource dismisses the view controller.</p><h4>Examples</h4><p>I have created a generic Resource type that makes it easier to wrap resources along with several examples. If you make resources that you would like to share, by all means send a pull request and I’d love to add it.</p><p>Check out my <a href="https://github.com/danielt1263/RxResource">RxResource</a> repository for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd149d2322f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert a Swift Delegate to RxSwift Observables]]></title>
            <link>https://danielt1263.medium.com/convert-a-swift-delegate-to-rxswift-observables-f52afe77f8d6?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52afe77f8d6</guid>
            <category><![CDATA[rxswift]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 12:10:48 GMT</pubDate>
            <atom:updated>2021-07-20T16:13:38.135Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the delegate protocols in the UIKit library already have reactive methods designed to convert the delegate into Observables. For those types in other libraries that haven’t been converted or if you are having to convert legacy code, you can create your own delegate proxy using the tools contained in the RxCocoa library.</p><p>The way you convert the delegate into Observables depends very much on the kinds of delegate methods and some of them simply can’t be converted. Not all methods can be converted; sometimes the delegate method requires that a calculation be made on the spot in order to return a value and Observables don’t allow that.</p><h3>The Basics</h3><p>First let’s cover the basic structure of every delegate proxy. Given a class that uses the delegate and a protocol that defines the delegate from some library:</p><pre>class Thing: NSObject {<br>    weak var delegate: ThingDelegate? = nil<br>}</pre><pre>@objc<br>protocol ThingDelegate: AnyObject {<br>    // some number of methods<br>}</pre><p>You first have to create the Proxy class. It’s easier to do this if your Thing type can conform to RxCocoa’s HasDelegate protocol, but it’s not a problem if you can’t make that work, it just means implementing a couple of extra methods in your proxy and the compiler will insert the stubs for you.</p><p>Here’s the basic shell of every delegate proxy class:</p><pre>class ThingDelegateProxy<br>    : DelegateProxy&lt;Thing, ThingDelegate&gt;<br>    , DelegateProxyType<br>    , ThingDelegate {</pre><pre>    init(parentObject: Thing) {<br>        super.init(<br>            parentObject: parentObject, <br>            delegateProxy: ThingDelegateProxy.self<br>        )<br>    }</pre><pre>    public static func registerKnownImplementations() {<br>        self.register { ThingDelegateProxy(parentObject: $0) }<br>    }<br>}</pre><pre>extension Reactive where Base: Thing {<br>    var delegate: ThingDelegateProxy {<br>        return ThingDelegateProxy.proxy(for: base)<br>    }<br>}</pre><p>Using the above as a base, everything else that is needed will depend on what methods are on the delegate. Are they optional or required? Do they pass a value to the delegate as one or more parameters or do they expect the delegate to return a value? Let’s try to cover each use case.</p><h3>Optional Method, Passes a Parameter</h3><p>The most common use case is that the method is optional and it passes one or more parameters to the delegate:</p><pre>@objc<br>protocol ThingDelegate: AnyObject {<br>    @objc optional func thing(<br>        _ thing: Thing, <br>        hasDoneSomething param1: String, <br>        with value: Int<br>    )<br>}</pre><p>In cases where the delegate receives the Thing, you can ignore the thing passed back to the delegate because the Rx system creates a different delegate object for each thing. The other value(s) passed into the method should be included in the Observable for use. Simply add something like this to your proxy and you are done:</p><pre>var hasDoneSomething: Observable&lt;(param1: String, value: Int)&gt; {<br>    delegate.methodInvoked(<br>        #selector(ThingDelegate.thing(_:hasDoneSomething:with:))<br>    )<br>    .map { ($0[1] as! String, $0[2] as! Int) }<br>}</pre><h3>Required Method, Passes a Parameter</h3><p>The next use case is when the method is required.</p><pre>@objc<br>protocol ThingDelegate: AnyObject {<br>    func thing(<br>        _ thing: Thing, <br>        hasDoneSomething param1: String, <br>        with value: Int<br>    )<br>}</pre><p>In this case the function may or may not be an @objc method; it doesn’t matter your code will be the same. When confronted with a required method, your delegate proxy must implement the method and it should use a Subject to forward the value(s) on to the Reactive operator.</p><p>So you add this to the proxy itself:</p><pre>func thing(<br>    _ thing: Thing, <br>    hasDoneSomething param1: String, <br>    with value: Int<br>) {<br>    hasDoneSomething.onNext((param1, value))<br>}</pre><pre>fileprivate let hasDoneSomething = <br>    PublishSubject&lt;(param1: String, value: Int)&gt;()</pre><p>And add this to the reactive extension:</p><pre>var hasDoneSomething: Observable&lt;(param1: String, value: Int)&gt; {<br>    delegate.hasDoneSomething<br>}</pre><h3>Method Returns a Value</h3><p>This use case requires you to return a value:</p><pre>protocol ThingDelegate: AnyObject {<br>    func thingNeedsSomething(_ thing: Thing) -&gt; String?<br>}</pre><p>In this case, it doesn’t matter whether the method is optional or not, you have to handle it the same way. These sorts of methods must be implemented in the delegate proxy and need to be converted into an Observer instead of an Observable.</p><p>Here’s what needs to go in your proxy. Notice that you have to provide a default value. Be sure that is the value that the caller uses if the method isn’t implemented.</p><pre>func thingNeedsSomething(_ thing: Thing) -&gt; String? {<br>    relay.value<br>}</pre><pre>fileprivate let needsSomethingRelay = <br>    BehaviorRelay&lt;String?&gt;(value: nil)</pre><p>And then in the Reactive extension put this:</p><pre>var needsSomething: Binder&lt;String?&gt; {<br>    Binder(delegate) { del, value in<br>        del.needsSomethingRelay.accept(value)<br>    }<br>}</pre><h3>Method both Passes a Parameter and Returns a Value</h3><p>Here’s where it gets tricky and you may not be able to provide an Observable. You can only do it if you know ahead of time all the values that will be passed in.</p><p>For example if the method looks like this:</p><pre>protocol ThingDelegate: AnyObject {<br>    func thingNeedsSomething(<br>        _ thing: Thing, <br>        for item: String) -&gt; Int<br>}</pre><p>You would have to know all the possible values that might be passed to item and what you would want to return in order to implement this method as an Observer.</p><p>Add this code to your proxy:</p><pre>func thingNeedsSomething(_ thing: Thing, for item: String) -&gt; Int {<br>    relay.value[item] ?? 0<br>}</pre><pre>fileprivate let relay = BehaviorRelay&lt;[String: Int]&gt;(value: [:])</pre><p>And then in your reactive extension add this code:</p><pre>var needsSomething: Binder&lt;[String: Int]&gt; {<br>    Binder(delegate) { del, value in<br>        del.relay.accept(value)<br>    }<br>}</pre><h3>Epilogue</h3><p>Creating a proxy for your delegates can be a bit of a pain sometimes but they really clean up the point of use and make everything much easier to understand. The next time you are confronted with a new delegate, instead of casting about on the internet trying to find a solution, you now have the knowledge to make the proxy yourself!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52afe77f8d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VIPER, RxSwift-ified]]></title>
            <link>https://danielt1263.medium.com/viper-rxswift-ified-1ec3ae8ab9a6?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec3ae8ab9a6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[viper-architecture]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 00:48:20 GMT</pubDate>
            <atom:updated>2019-11-05T01:57:43.099Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/danielt1263/Rx-VIPER-ToDo">I have committed a new repository as an example of using Rx to implement the VIPER architecture.</a> This is another one of my “follow along with the commits” articles which means that you should back up to the first commit and examine the code from each commit while reading the associated part of the article.</p><p>As far as I know VIPER was first described in <a href="https://www.objc.io/issues/13-architecture/viper/">Architecting iOS Apps with VIPER</a> back in June 2014. I decided to revisit this pattern and see how it can be adapted to live in our new, more functional and reactive world.</p><p>I have re-implemented the sample that came with the article above, but I also want to take this time to discuss a bit about the process of developing a program with the idea of documenting some of the non-code processes involved in creating an application. (This first part is a reprise of my <a href="https://medium.com/@danielt1263/an-aside-before-code-is-written-321883956f12">previous article</a> with specific details about this particular project.)</p><h3>Definition Phase</h3><p>For the purposes of this application, we only have one user type and one entity type. The former we will call <em>User</em> and the latter will be <em>ToDo</em>. Now let’s consider the actions. Since this is just a sample app we will only allow the create and read actions. Here are our user stories.</p><ul><li>As a User, I can create a ToDo.</li><li>As a User, I can read all ToDos due this week and next.</li></ul><h3>Design Phase</h3><p>In our case, we are expecting two screens. We will call them the <em>List</em> and <em>Add</em> screens. In the process of drawing them out, we have identified another user story as well as steps for all of them. The new story acknowledges the fact that creating a ToDo is a multistep process from the user’s perspective and gives the user the ability to abort the create action.</p><pre>(-) As a User, I can create a ToDo.<br>    From the List screen:<br>        1) Tap the add button to display the Add screen.<br>        2) Enter a title and date of a ToDo (both are required.)<br>        3) Tap save button to save ToDo and dismiss ToDo screen.<br>(-) As a User, I can cancel the create ToDo action.<br>    From the Add screen:<br>        1) Tap cancel button to dismiss Add screen without saving.<br>(-) As a User, I can read all ToDos due this week and next.<br>    From the List screen:<br>        * ToDos should be in date order.<br>        * ToDos should be grouped in the following categories:<br>            Today, Tomorrow, Later This Week, and Next Week.</pre><h3>Development</h3><p>We have a solid understanding now of what the user can do and we know what order we are going to develop those features in. We also have detail designs for the screens needed (at least for the first user story) and a list of fonts and colors that will be used throughout the app. Now it’s time to start development.</p><p>Before talking about how to adapt VIPER to Rx, I want to clear up a misconception about the architecture. Some people assume that there must be a VIPER (View, Interactor, Presenter, Wireframe) stack for every screen, but that is not at all true. Sometimes a single screen might be involved in multiple user stories at the same time and so will have several interactors. Sometimes a screen might be used for several different stories and have multiple Wireframes and Presenters associated with it. Lastly, sometimes multiple screens might be involved in a single user story and then one Wireframe will display several screens.</p><h3>Story 1, Step 1: Tap the add button to display the <em>Add</em> screen.</h3><p>In the first commit, I am implementing the first step of the first user story, “Tap the add button to display the <em>Add</em> screen.” Of course a lot has to be done for this simple step because in order to tap that add button, we need an application. Since the user story starts on the <em>List</em> screen, we need to create that as well, but only in so far as to give it an add button. Notice I haven’t fleshed out the rest of the screen. I went ahead and laid out the entire <em>Add</em> screen since I know I need it for the rest of this story. Also, since this is the step that displays the <em>Add</em> screen and the detail-design calls for a special presentation animation I did that here.</p><p>With the original conception of VIPER, each component was a class with several functions. In Rx things are a bit different. Here each component tends to be a single function. So I have the files named based on the component they represent, but each file only contains a single exposed function and possibly some private helper functions.</p><p>When the app starts up, the flow is as follows:</p><p>1. The ListWireframe is given control.<br>2. Since the storyboard has already displayed the <em>List</em> screen, the wireframe only needs to install the presenter into the view controller’s buildOutput function.<br>3. The ListViewController eventually loads, creates its Input object and then passes that input to the buildOutput function.</p><p>When the user taps the add button, the flow is as follows:</p><p>1. The addItem emits a next event to the list presenter.<br>2. The list presenter maps that to an add ListAction and emits that to the wireframe.<br>3. The list wireframe catches the add action and calls displayAdd which is in the AddWireframe.swift file.<br>4. The add wireframe instantiates the add view controller and presents it.</p><h3>Story 1, Step 2: Enter a title and date of a ToDo (both are required.)</h3><p>Much of the functionality of this commit was actually added in the last commit since I laid out the <em>Add</em> screen. However, to help ensure the stipulation that both title and date are required for saving, this is a good time to make sure the save button is only enabled if there is valid input. This is our first real bit of logic so I went ahead and added tests. Tests aren’t often added to sample code so I thought it would be a nice touch.</p><p>You will see that the logic is all in the presenters so that’s what is tested. In a properly constructed VIPER system, all of the logic will be in the presenters and interactors. I expect to have a test case for each user story.</p><h3>Story 1, Step 3: Tap save button to save ToDo and dismiss ToDo screen.</h3><p>For this step, we created our first interactor. We have also discovered a path not mentioned in the user stories. We need to outline what happens if the save fails. As mentioned, we <strong>update the user stories</strong> with this newly discovered information.</p><pre><br>(-) As a User, I can create a ToDo.<br>    From the List screen:<br>        1) Tap the add button to display the Add screen.<br>        2) Enter a title and date of a ToDo (both are required.)<br>        3) Tap save button to save ToDo and dismiss ToDo screen.<br>    Error: If the save fails, instead of dismissing the ToDo screen, <br>           an Alert screen displays explaining the error.</pre><p>One of the defining features of VIPER is that <em>only</em> Interactors work with Entities and the DataStore, the Wireframe injects the DataStore into the Interactor, and the Presenter knows nothing about the DataStore <em>or</em> the Entities.</p><p>You will notice that the presenter doesn’t create a Todo object, instead it just passes enough information to the Interactor for <em>it</em> to create the Todo object which then passes it to the DataStore. Then the DataStore converts the Todo object into a form that is savable and saves it.</p><p>It’s interesting to note that up to this point, our code has been indistinguishable from an MVVM-C architecture (other than the names of things.) VIPER adds an extra level of indirection between the interactor (view model) and the entities/data store. In MVVM-C, the view model works directly with them both. Personally, I’m not sure if this extra level of indirection is useful. Even in an application this small, I’m left wondering where I should change the date of the object to the startOfDay? Should it be done in the presenter or in the interactor?</p><h3>Story 2, Step 1: Tap cancel button to dismiss Add screen without saving.</h3><p>Since the screen and button for this story have already been laid out, it’s just a matter of hooking them up. We add the cancel button to the UI’s input, and then bind it directly to the wireframe’s Observable.</p><h3>Story 3: Read Todos.</h3><p>An important thing to notice at this point is all the different ways a “Todo” is represented in the system, even in something as simple as this example program.</p><ul><li>There’s the way the DataStore represents todos internally (in our case, as a plist structure and if we had used CoreData then as NSManagedObjects).</li><li>There’s the way todos are represented internally by the interactors (and externally by the DataStore) as Todo structs.</li><li>There’s the way todos are represented internally by presenters (and externally by interactors.) The list presenter uses UpcomingItem.</li><li>Lastly, theres the way todos are represented internally by view controllers (and externally by presenters.) The list view controller uses UpcomingDisplaySection and UpcomingDisplayItem.</li></ul><p>Again I am struck with the difference in complexity between MVVM-C and VIPER; in the former there would only be three different representations of a todo rather than four. Maybe in a larger project it would make more sense; presumably we would find re-use opportunities that wouldn’t otherwise exist? In MVVM-C I’m inclined to create such abstractions when they are discovered rather than assuming them at the outset.</p><p>For this story, you will see that most of the changes/additions are mostly dedicated to morphing the data in the stored plist into data the table view can understand over the four stages mentioned above. I also had to modify the AddWireframe so it could notify its parent about successful updates and pass that into the List presenter so it will know when to re-get the list of items.</p><h3>Epilogue</h3><p>This was an interesting exercise and I learned a lot about both VIPER and MVVM-C while doing it. Remember, the point of this article is to <em>follow along with the commits.</em> If you aren’t doing that, you won’t get the most out of it. Be sure to check out the repository and follow along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec3ae8ab9a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Aside: Before Code is Written]]></title>
            <link>https://danielt1263.medium.com/an-aside-before-code-is-written-321883956f12?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/321883956f12</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[process-improvement]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Thu, 19 Sep 2019 11:17:50 GMT</pubDate>
            <atom:updated>2019-09-19T18:28:03.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of my articles have been very code heavy but for this one I want to take time to discuss a bit about the process of developing a program, with the goal of documenting some of the non-code processes involved in creating an application. As a companion to Jody Haneke’s article <a href="https://www.jodyhaneke.com/waterfall-process-agile-methodology-design-thinking/">“The Importance of Definition, and Redefinition in Agile Software Methodology”</a>, this article looks at the phases of software creation from a developer’s perspective.</p><h3>Definition Phase</h3><p>The first step in developing an application is to decide what the application is supposed to do. It doesn’t have to be a complete list, but it should include all the functionality that immediately comes to mind.¹ This functionality is specified by a number of User Stories; they consist of a number of entities and they allow a number of different types of user to perform a number of actions with those entities.</p><p>Every application will have different entities and different types of user, but most applications are of a CRUD nature. CRUD is an acronym for Create Read Update Delete which are the actions that can be performed on entities. Every entity does not have to have every action, but every action should be considered. Sometimes only certain types of users will be able to perform certain actions on certain entities.</p><p>At the end of this process, you will have a list of “user stories”, each of which will define a type of user, an entity and an action that can be performed on that entity.</p><p>The deliverable is a list of these user stories along with a list of user types, entities and connections between entities.² (Users may also be represented by entities in the application.)</p><h3>Design Phase</h3><p>The next step is to draw out a <a href="https://en.wikipedia.org/wiki/Website_wireframe">wireframe</a>. This is often done for websites, but it’s also <a href="https://www.upwork.com/hiring/for-clients/importance-of-wireframing-mobile-apps/">important for mobile apps</a>. Also during this phase, the processes involved in all the user stories will be augmented with the steps the user needs to go through in order to complete the user story.</p><p>These user story steps will start on a particular screen and will detail the actions the user must take in order to complete the story. (i.e., “from screen X, tap button Y, enter Z information, and so on until completion.”)</p><p>This phase will produce a list of screens, the functionality (inputs &amp; outputs) available in each screen, connections between screens, as well as a path for each user story from above.</p><p>It’s important to remember that this is <em>not</em> a waterfall process. It is quite likely that new user stories will be discovered during this phase along with new entities and users. As they are discovered, a decision will have to be made as to whether these new stories and screens must be in the current version of the application, or can be set aside for a future version.³ If it is determined that they must be included in the current version, then update the wireframe and user story list to include them, and make sure that all stake-holders have buy-in regarding the added scope. These additions will affect costs and deadlines and it’s unprofessional to ignore that fact or try to hide it.</p><h3>Build Phase</h3><p>Now it’s time to decide in which order the user stories will be developed. During this process it’s important to take into account any dependencies between stories. If you have stories that deal with sub-entities of some entity then they need to come after the stories about the entities. Each story starts on a particular screen so it is sometimes helpful to group stories by the screen they start on. Lastly, it’s generally easier to develop stories in CRUD order for a particular entity.</p><p>The process of developing a user story isn’t just about writing code, each screen also needs a detail-design and decisions need to be made about application wide fonts and colors. All of this can generally be done in parallel; however, it’s best if the detail design of a screen comes before development so that code doesn’t have to be revisited.</p><p>And again because this is so important: Even during <em>this</em> process, new user stories, entities and users could be discovered (especially in regard to error paths through stories,) and maybe new screens will be required. If the stake-holders decide they must be in the current version of the application then <strong>update the previous deliverables</strong>.</p><ol><li>At Haneke Design, where I am the director of development, we kick off a new project with a Workshop where a Designer, Developer and others sit down with the idea person to define the user stories, as well as design themes.</li><li>A side note about naming things. In order to foster communication in a team it’s important to be consistent about what things should be called. Naming is hard, but once you pick a name, stick with it. If you absolutely <em>must</em> change it, change it everywhere, including in code.</li><li>At Haneke Design, we cycle through this process for every version of the application in development, usually once ever three months but, depending on customer, it may be more or less often.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321883956f12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating RxSwift Into Your Brain and Code Base: Part 2]]></title>
            <link>https://danielt1263.medium.com/integrating-rxswift-into-your-brain-and-code-base-part-2-a4f16de628bf?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f16de628bf</guid>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sat, 13 Apr 2019 02:15:10 GMT</pubDate>
            <atom:updated>2019-04-15T13:36:10.862Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@danielt1263/integrating-rxswift-into-your-brain-and-code-base-1a790c36c36d">part 1</a> of this series we took one of Apple’s sample apps and added RxSwift to it. In doing so, we replaced all the IBActions, Delegates, Notifications, and KVO calls with their RxSwift counterparts. However, we didn’t really change the semantics of the code, it’s still just as imperative and one could even argue that it’s more confusing than the original. You might recall that in part 1 I commented that a lot of the complexity of an iOS app comes from having to integrate all the different observation systems into a cohesive whole. Now that we are only using <em>one</em> observation system, let’s see what we can do to get rid of that extra complexity and along the way, make our code more declarative. We will even write tests for the logic as we break it away from the effects the code performs.</p><p>As a reminder, you need to follow along in the <a href="https://github.com/danielt1263/RxMultipeerGroupChat">GitHub repo</a> in order to get the best out of this article. The first eight commits in the repo are covered in part 1 so let’s start there. Enough preamble, we’re off…</p><h3>Consolidating the ProgressObserver</h3><p>Since this is more about changing the semantics of the code, the process is going to be less formulaic. Basically we are looking for places where we are binding/subscribing inside another bind/subscribe, or where we are manipulating a Subject inside a bind/subscribe. For this first step I will focus on the ProgressObserver class since it only has two binds in it. We’ll start small.</p><p>Here, the only function is the init and the exposed properties are all lets. This immediately tells us that this entire class could likely be replaced by a single function that takes in the same parameters as the init method and returns the properties as a tuple. Further investigation reveals that name and progress properties aren’t used outside the class and could be made private so the only property we actually need to worry about is the changed computed property. Basically, the only reason this class existed in the original code was to convert from using KVO to a delegate. Now that such conversion is unnecessary, the entire class has become superflous.</p><p>As a result, the class functionality has been moved into a Progress extension function. Tests have also been written to ensure correct logic.</p><h3>Simplifying the ProgressView</h3><p>Let’s continue to follow the chain from the Progress object into the ProgressView.</p><p>First we inline the three functions that used to be a part of the delegate by moving their contents into the subscribe method. We see that there are no Subjects in them, but the terminus in the subscribe’s onNext closure is already a bindable property provided by RxCocoa, so we can make some simplifications there. We also find that the onError and onCompleted closures are merely debug messages. In the interest of code parity I will keep the print messages, the do() operator is great for such things.</p><h3>Simplifying the SettingsViewController</h3><p>Boy there’s a lot of logic in this class. The astute among you will notice that the displayName and serviceType validation doesn’t seem to exist in the Objective-C sample code from Apple. They checked validation by using that language’s try/catch system which isn’t available in Swift so I resorted to manually writing the validation logic. It would be nice though if it were more testable. So we will now move it to its own function. There are a lot of conditionals in this function and to achieve <a href="https://en.wikipedia.org/wiki/Basis_path_testing">basis path coverage</a> would require 13 tests. I’ll leave that as an exercise for the reader. At least now the logic is out where it can be tested without creating a SettingsViewController.</p><p>Further inspection shows that, though the done button’s bind function uses self, it does so in order to access the displayName and serviceType strings. So let’s expand our chain to push just those values in. Once we do this and then move the doneTapped code into the bind&#39;s closure we end up with:</p><pre><strong>let</strong> inputValues = Observable.combineLatest(displayNameTextField.rx.text.orEmpty, serviceTypeTextField.rx.text.orEmpty) { (displayName: $0, serviceType: $1) }</pre><pre>doneButton.rx.tap<br>    .withLatestFrom(inputValues)<br>    .bind(onNext: { [weak <strong>self</strong>] displayName, serviceType <strong>in<br>        if</strong> isValid(displayName: displayName, serviceType: serviceType) {<br>            <strong>self</strong>?._didCreateChatRoom.onNext((displayName, serviceType: serviceType))<br>        }<br>        <strong>else</strong> {<br>            <strong>let</strong> alert = UIAlertController(title: &quot;Error&quot;, message: &quot;You must set a valid room name and your display name&quot;, preferredStyle: .alert)<br>            alert.addAction(UIAlertAction(title: &quot;OK&quot;, style: .cancel, handler: <strong>nil</strong>))<br>            <strong>self</strong>?.present(alert, animated: <strong>true</strong>, completion: <strong>nil</strong>)<br>        }<br>    })<br>    .disposed(by: disposeBag)</pre><p>Whenever I see an if...else block in a bind/subscribe function I immediately look to using Observable.filter instead. This will mean we need two observables, one for the true branch and one for the false branch. In the true branch we are just connecting to the subject so we can bind to it directly. In this instance we can’t get rid of the subject because the chain that feeds it doesn’t come into existence until after viewDidLoad is called.</p><p>Then there’s the matter of moving our logic out of the view controller so it can be tested independently. The inputs to the logic are the text of the two fields and the done button’s tap. The outputs are to inform the subject when a chat room can be created and to inform the view controller when an error alert needs to be displayed. Note, I didn’t say “either/or” here. The done button can be tapped multiple times and the function must be able to respond with both depending on the logic.</p><p>Congratulations are in order here. We just created our first view model.</p><h3>Simplifying the SessionContainer `received` Observable</h3><p>The first thing to do here is to inline the delegate functions into their function blocks. Once that is done, we can see that there are three different binds that all affect the _received subject. You want to avoid that as much as possible; it’s a very imperative thing to do. Better would be to have a single chain that expresses the invariant of when/why the subject should emit.</p><p>In all three cases, we are taking different sorts of data from the session object and converting them into Transcripts, and once we inline the functions we see that all the real work is being done inside the bind methods. Let’s extract that work into maps and then extract the logic into single, testable, operators. So that the only things left in the bind functions are the subject.</p><p>To complete this simplification, we only need to remove the binds, merge the three observables, and bind the merged observable once. Wait, we are in the init function, so we can get rid of the subject completly and directly assign to the received observable.</p><h3>Simplifying the SessionContainer `didFinishReceivingResource` Closure</h3><p>Here we see error objects, but we have to be careful because Observable errors will shutdown a stream and we don’t want that happening. Also, like earlier, we see a condition inside a bind. Actually, there are two ways the bind can error for a total of three different possible outputs.</p><p>Three different outputs calls for three different observable chains. Also, we see that a side effect (copying the image) happens where the results are required for later. Side effects are for beginnings and ends of observable chains, so we need to create an observable in which this side effect is performed. This became the copyItem(resourceName:localURL:) function. Since this effect can error, and we don’t want the error to break the chain, we use materialize() here.</p><p>We can’t get rid of the _update subject just yet because it is also used in the send(imageURL:) function.</p><h3>Consolidating the MainViewController’s `sendMessageButton` Output</h3><p>I see that this program suffers from “Massive View Controller” syndrome. Despite it’s small size, the main view controller is playing god. RxSwift isn’t an architecture and doesn’t avoid this anti-pattern on its own, but it <em>does</em> provide opportunities to use architectures that will help avoid the problem. That said, it isn’t the goal of this article to discuss architecture, we are only looking to simplify the code we have.</p><p>For a first step in simplifying the MainViewController, I see that there are two different observable chains that affect the sendMessageButton&#39;s isEnabled property. Let’s move those together. This is something I call Output Centric programming. The idea is that there is a single place in the code to see all the inputs that can affect a single piece of output. By doing this, the chain for that output becomes its invariant. It makes explicit exactly what behaviors affect this particular output and how they do so.</p><p>At this point, you might wonder about the text in messageComposeTextField. In one chain we listen to editingDidEnd and set the text to an empty string, while in the other chain we listen to the same event and read the text to use it. This is safe because programmatically changing the text does not cause an event to emit. That said, there is some odd behavior for the RxCocoa text attribute because it emits on editingDidEnd events. Since we want to emit false on editingDidEnd regardless of the contents of the field, we need to guard against that extra emission. Therefore we have to add the distinctUntilChanged() function.</p><h3>Separating the text clearing behavior</h3><p>In the spirit of the output centric approach mentioned above, we should limit the behavior in a subscribe/bind block as much as possible. To that end, let’s create a new observable chain just for clearing the text field.</p><h3>Simplifying and Correcting the Send Text Feature</h3><p>While writing the above and making the refactoring, I realized that the sample source has a rather subtle bug in it. The text is sent when the textField’s editingDidEnd event emits which happens when the field resigns first responder status. Tapping the send button or return on the keyboard causes the field to resign, but the field will also resign when some other view controller is presented (which would happen when the user taps one of the other buttons on the screen.) This surprising behavior slipped through the original sample because of the indirectness of the code. Do we really want to send whatever text is in the field whenever the keyboard drops? Not likely. Do we really want the keyboard to drop every time the user sends text? Also not likely.</p><p>Correct behavior is to send the text when the send button or return key is tapped and keep the keyboard up so the user is ready to send more text. We can fix that simply by replacing messageComposeTextField.rx.controlEvent(.editingDidEnd) with sendMessageButton.rx.tap and removing the code that causes the keyboard to dismiss in those situations. So let’s do that now.</p><h3>Inlining All the Things!</h3><p>You might have noticed that I’m doing a lot of inlining of functions in the main view controller. Let’s take a break from the hard stuff and inline all the functions that are only called once and only in an already existing closure. We will keep createSession() and insert(transcript:) for now since they are referenced from multiple places, but the rest of the private functions are going away.</p><h3>Removing Nested Subscribes: `browseForPeers`</h3><p>Seeing a disposeBag referenced inside a subscribe closure is a sure sign that we have some inapproprate nesting. I’ll start at the top and deal with the chain that presents the MCBrowserViewController.</p><p>The createWithParent function is cribbed from sample code that is distributed with the RxSwift package. There’s a lot of good stuff in there.</p><h3>Extracting the UIAlertController Presentation</h3><p>What happens when the sendPhotoButton is tapped? The first bit is easy, request authorization, but then we get into this massive bind closure. We know what happens inside that closure because we have run the program an know what needs to happen, but reading it is not very obvious. It creates and presents an action sheet to get configuration parameters for the image picker, then creates and presents the image picker to get the user’s image, then switches to a background thread to save the image and send it to the session container, then switches back to the main thread to insert the generated transcript into the table view. That’s entirely too much work for one closure.</p><p>Also, notice how I presented the behavior as a list of steps, but when you look at the code you see that these steps are deeply intwined. <a href="https://medium.com/@danielt1263/encapsulating-the-user-in-a-function-ec5e5c02045f">I have already written a blog post about this sort of code.</a> That post was in the context of Promises, but the same ideas apply to Observables.</p><p>Fixing this closure is a big job so we will do it in stages starting at the top: presenting the UIAlertController to figure out how to configure the image picker.</p><h3>Extracting the UIImagePickerController Presentation</h3><p>This will be the third view controller that we have presented so it should be pretty obvious what’s going on here. I also cleaned up the UIAlertController presentation closure a bit.</p><h3>Un-nesting `didFinishPickingMediaWithInfo`</h3><p>The next step is small but highly instructive so I am giving it its own commit. Whenever you see a bind/subscribe where the first thing that happens within it is another bind/subscribe, you know a simple flatMap wrap like what I do in this commit is the right choice. Always keep an eye out for this sort of code.</p><h3>Taking Advantage of RxSwift Async Abilities</h3><p>With the above, we have gotten rid of all the nested binds but there’s still a lot of code in that bind closure. It dismisses the image picker, switches to a background thread to save and send the image then switches back to the foreground thread to insert the image into the tableView. Surely we can do more here…</p><p>In this commit we manage to tease out what little logic there is in this chain by creating the imageData(from:) and imageUrl(with:) functions, but this observable chain is almost exclusively side effects hence all the flatMaps.</p><p>We also found a couple of other places that were using DispatchQueues and changed them to use Schedulers.</p><h3>Epilogue: What’s Left?</h3><p>There’s certainly more that can be done! I haven’t wrapped the table view’s data for example. Also, I could re-architect the code to use a MVVM approach rather than its current ad-hoc setup. Lastly, I have separated some logic out of the main view controller but I didn’t add the tests yet.</p><p>I will likely refine the code when time permits. Expect to see more pull requests and I will include commit comments that explain the changes. Also, pull requests are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f16de628bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating RxSwift Into Your Brain and Code Base]]></title>
            <link>https://danielt1263.medium.com/integrating-rxswift-into-your-brain-and-code-base-1a790c36c36d?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a790c36c36d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[rxswift]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 13:29:34 GMT</pubDate>
            <atom:updated>2019-04-15T15:03:37.396Z</atom:updated>
            <content:encoded><![CDATA[<p>So you have recently learned about RxSwift and RxCocoa. You have read some tutorials and maybe even a book or two. You have a program already in existence or maybe you are starting a new app but you can’t afford to do too much experimentation. Where do you go from here?</p><p>I have tutored lots of people in RxSwift over the years and it has been my experience that if they try to go “full Rx” right away they will end up with a mess of code that is harder to understand than anything they have ever written. Because of this, I recommend integrating Rx into your code slowly and with intention.</p><p>In order to effectively integrate Rx into your app you first have to identify two kinds of functions: pull type and push type. The first type of function returns values when called and is used to “pull” or get information from objects. The second type takes values as parameters and doesn’t return anything and is used to “push” or set information into objects. (Watch out, there are also functions that do both.) Rx strongly favors push type functions, so if your style also favors push functions, then the integration will be more effective.</p><p>If the code base you are starting with favors a push style, then you will find it much easier to integrate Rx and will be able to do it more fully. Fortunately, Apple’s frameworks also favor push style code, so that should help reduce the friction.</p><p>For this post, I assume you have already read some tutorials and understand what an Observable, Observer and Subject are. I also assume that you know at least how merge, map, flatMap and filter work and are comfortable looking up other operators as you go along.</p><p>There are seven different systems used in iOS code to push data from one object to another:</p><ul><li>closures</li><li>target/action (UIControl aka IBAction)</li><li>delegates</li><li>notifications (NotificationCenter)</li><li>KVO</li><li>setting variables</li><li>sub-classing abstract base classes</li></ul><p>A lot of the complexity of writing an application comes from trying to integrate these various systems into a unified whole. Each of the systems individually is simple to use, but weaving them together makes our code complex. One of the benefits of using RxSwift is that it wraps all of the above systems into a single powerful mechanism, thus making our code less complex overall.</p><p>Knowing the above gives a clue on how to go about integrating RxSwift into an existing project. If RxSwift can replace all those other technologies, then to integrate means to replace them with it. Once this is done, we will be able to make the code more declarative and less complex.</p><p>For this article, I’ve decided to use an old sample from Apple, <a href="https://developer.apple.com/library/archive/samplecode/MultipeerGroupChat/Introduction/Intro.html">MultipeerGroupChat</a>. This code was originally written for iOS 7 and Objective-C but that won’t do for our purposes so I updated the code to Swift.</p><p>If you look at the first commit of the sample code in my <a href="https://github.com/danielt1263/RxMultipeerGroupChat">GitHub repo</a>, you will find a rather straightforward reimplementation of Apple’s sample code. There are some quirks about the code (not the least of which stems from the fact that all phones were the same width back then,) but our job isn’t to fix those. Rather our goal will be to integrate RxSwift into the program and along the way see how it gets transformed.</p><p>Each of this article’s section titles corresponds to a commit in the repository so it’s easy to follow along in the code. Be sure to use the code analysis tools in GitHub or Xcode to compare before-and-after changes. If you aren’t doing this, you won’t be able to understand what’s going on.</p><p>I picked this particular sample because it has a nice mix of target/action, delegates, notifications and even a sprinkling of KVO so there’s a lot to work with. Let’s get started, shall we?</p><h3>Replacing IBActions</h3><p>For our first step, we will start with something easy — replacing IBActions with observables. This is as simple as:</p><ol><li>Make sure that the input that triggers the action is an IBOutlet in the view.</li><li>Make sure that RxSwift and RxCocoa have been imported into the view’s file.</li><li>Make sure the view has a DisposeBag</li><li>In the view’s initializer (for a UIView this would be the awakeFromNib method, for a UIViewController it would be the viewDidLoad method) subscribe to an Observable on the input that just calls the action.</li></ol><p>As an example of this, in the MainViewController of our sample, there is an @IBAction called browseForPeers(_:). We see that the button that triggers this action isn’t an IBOutlet so first we do that, then we put this in the viewDidLoad:</p><pre>browseForPeersButton.rx.tap<br>   .bind(onNext: { [weak self] in self?.browseForPeers() })<br>   .disposed(by: disposeBag)</pre><p>In this case, the browseForPeers method takes a sender which we don’t need so we update the function signature from @IBAction func browseForPeers(_ sender: Any) to simply func browseForPeers().</p><h3>Replacing Delegates: Removing App Specific Protocols</h3><p>This is a much larger topic and there are a lot of delegates in the code we are working with, so I will break it up into stages. We see two basic sorts of delegates in this code — those provided by libraries (for e.g., MCBrowserViewControllerDelegate) and those created custom for this app (e.g., SessionContainerDelegate.) For the first sort we are forced to use the DelegateProxy class provided by RxCocoa; for the latter sort I recommend doing away with them completely.</p><p>We will start with removing the special purpose delegates. The basic process is again pretty mechanical.</p><ol><li>Create a private PublishSubject for each function in the delegate protocol.</li><li>Create a computed property that returns each of the publish subjects as an observable.</li><li>Remove the delegate property and replace calls to it to onNext calls to the correct publish subject.</li><li>In the object that conforms to the delegate, remove the protocol conformance and replace with binders to each observable created in step 2.</li></ol><p>A simple example is the SettingViewControllerDelegate which only has one method. The purpose of the protocol is to push out the new displayName and serviceType strings so our observable will want to do likewise.</p><p>We create the new didCreateChatRoom Observable:</p><pre>var didCreateChatRoom: Observable&lt;(displayName: String, serviceType: String)&gt; {<br> return _didCreateChatRoom.asObservable()<br> }</pre><pre>private let _didCreateChatRoom = PublishSubject&lt;(displayName: String, serviceType: String)&gt;()</pre><p>And then call its onNext function, instead of the delegate’s method, which will allow us to do away with the protocol. Meanwhile in the MainViewController, we bind to the new observable and remove the protocol conformance. You will notice that when I removed the conformance, I didn’t actually remove the function. Instead I just changed its signature so it no longer accepts a SettingsViewController and called that function from within the bind closure.</p><p>I need to make a special mention of the ProgressObserver&#39;s delegate. It contains three functions (changed, canceled, completed) and the semantics of them went well with those of an observable event (next, error, completed) so instead of making three observables, I just went with one.</p><h3>Replacing Delegates: Wrapping iOS provided protocols</h3><p>Sadly, creating wrappers using the DelegateProxy class provided by RxCocoa is outside of the scope of this article. I will have to give it its own treatment later. However, once you have them, replacing the protocol conformance with observables is something that we will cover. The steps are:</p><ol><li>Remove the protocol conformance tag from the class/extension.</li><li>At the point where the delegate was getting set, replace that setter with the needed subscriptions to the various observables.</li></ol><p>For example, getting data from a UIImagePickerController requires that we add the rx.didCancel and rx.didFinishPickingMediaWithInfo binders.</p><pre>imagePicker.rx.didCancel<br>    .bind(onNext: { [weak self] in<br>        self?.imagePickerControllerDidCancel()<br>    })<br>    .disposed(by: disposeBag)<br>imagePicker.rx.didFinishPickingMediaWithInfo<br>    .bind(onNext: { [weak self] info in<br>        self?.didFinishPickingMediaWithInfo(info)<br>    })<br>    .disposed(by: disposeBag)</pre><p>Another special mention needs to be made here, this time about UITextFieldDelegate. This particular delegate is often used incorrectly (even in Apple sample code) and can almost always be replaced by IBActions. That is the case here and since we already covered IBActions, I have simply made the replacement directly to observables.</p><h3>Replacing Notification Observers</h3><p>There are a number of problems with the sample code surrounding keyboard display and dismissal. I assume that the bugs exist because of changes in how the keyboard notifications work. Rather than just a mechanical replacement, we are forced to do a rewrite of the moveToolBar function.</p><h3>Fixing a photo capture bug</h3><p>During routine testing, I noticed that the app was unable to capture and send photos. I realized the problem was two fold. First, the operating system now requires the app to explicitly ask for permission to access photos, and second, the UIImagePicker delegate proxy I cribbed from the RxSwift sample code is out of date. To fix these, I wrote my own UIImagePicker delegate proxy, included the required permission strings, and added the request authorization method. This later is a good example of how to wrap an OS function that requires a callback and returns Void.</p><pre>extension Reactive where Base: PHPhotoLibrary {<br>    static var requestAuthorization: Observable&lt;PHAuthorizationStatus&gt; {<br>        return Observable.create { observer in<br>            Base.requestAuthorization { status in<br>                observer.onNext(status)<br>                observer.onCompleted()<br>            }<br>            return Disposables.create()<br>        }<br>    }<br>}</pre><h3>Replacing KVO</h3><p>This app uses KVO inside the ProgressObserver class to observe the Progress object. It observes two properties of the progress object, cancelled and completedUnitCount. Whenever either of them is updated, the appropriate bound observer will be called. You will see that now each observed key-value gets its own closure rather than having to route all of them through a single function and since the dispose bag takes care of cleanup for us, we can do away with the deinit function.</p><h3>Interlude</h3><p>Wow, that was a lot of work and a pretty big word count for some fairly mechanical code refactoring. I did some runs of the app throughout the refactoring but by and large I knew that behavior wasn’t changing so I wasn’t concerned. It would be nice to test the logic, but the logic was so interwoven with the effects and so much of the code was about translating from one observation system to another that, up to this point, writing the tests would have been very difficult.</p><p>Now that we have most of the code converted to using RxSwift, we can start removing a lot of it and tease out the logic for testing. When you are ready, check out <a href="https://medium.com/@danielt1263/integrating-rxswift-into-your-brain-and-code-base-part-2-a4f16de628bf">Part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a790c36c36d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxSwift’s Many Faces of FlatMap]]></title>
            <link>https://danielt1263.medium.com/rxswifts-many-faces-of-flatmap-5764e6c2018c?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5764e6c2018c</guid>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[reactivex]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sun, 03 Feb 2019 20:26:00 GMT</pubDate>
            <atom:updated>2020-04-09T02:18:50.943Z</atom:updated>
            <content:encoded><![CDATA[<p>With most types that have a flatMap method (for example Array and Optional) there is no time element involved and thus there is only one way to flatten them, but RxSwift’s Observable type has a time element which gives us more possibilities on how to flatten a group of them. In this article we will explore the four different ways of flattening an Observable.</p><h3>The Value of flatMap</h3><p>The flatMap method makes it easy for us to do a couple of different things that would have been hard to do otherwise. First, it allows us to increase the number of events being produced by an Observable stream. Second, it allows us to perform some asynchronous work as part of the stream.</p><p>For an example of the first idea we have this:</p><pre>let string = Observable.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>string<br>    .flatMap { Observable.of(&quot;\($0)-x&quot;, &quot;\($0)-y&quot;, &quot;\($0)-z&quot;) }<br>    .subscribe(onNext: { element in<br>        print(element) // this prints 9 values.<br>    })</pre><p>An example of the second idea is something like this:</p><pre>string<br>    .flatMap { URLSession.shared.rx.data(request: URLRequest(url: URL(string: &quot;<a href="http://myserver.com/api/get_user?id=\($0)">http://myserver.com/api/get_user?id=\($0)</a>&quot;)!)) }<br>    .subscribe(onNext: { element in<br>        print(element) // this prints the result of the 3 network requests.<br>    })</pre><p>The RxSwift library provides four ways to flatten observables and it’s important to understand the differences.</p><h3>The Choices and Their Differences</h3><p>The RxSwift library gives us four different flatMap methods:</p><p>flatMap</p><p>The basic flatMap merges the results from all the sub-Observables into one Observable. Every time the source emits a value, flatMap will create a new sub-Observable and subscribe to it, merging results of all the sub-Observables into one. There is no guarantee about the order of the outputs. If any of them emit an error, it will immediately shut down all the others and emit the error. The operator won’t emit a completed event until the source and all the sub-Observables have emitted completed events.</p><p>flatMapLatest</p><p>This is probably the most commonly used flatMap. When its source emits the first value, flatMapLatest will create a new sub-Observable and emit its next events. Unlike the flatMap above, if the source emits another value before the sub-Observable completes, then flatMapLatest will dispose the current sub-Observable before starting the new one.</p><p>It’s the cancelation ability that makes this operator so popular. If you don’t need the results of the network request anymore because the inputs have changed, then flatMapLatest is what you want.</p><p>flatMapFirst</p><p>Occasionally, you <em>don’t</em> want to cancel the sub-Observable and instead you would rather ignore events from the source until the sub-Observable is done. This is what flatMapFirst is for. Like flatMapLatest, it only allows one sub-Observable at a time. Unlike flatMapLatest, it will not cancel an ongoing sub-Observable. Instead it ignores events from the source until the sub-Observable is done.</p><p>concatMap</p><p>Like flatMap, the concatMap operator will create a sub-Observable for every event from the source, but this one guarantees the order of the output. It will only subscribe to one sub-Observable at a time and won’t subscribe to the next sub-Observable until the current one completes. Unlike flatMapFirst, it won’t ignore other events, instead is will buffer them to use when it’s ready.</p><h3>Summary</h3><p>These four flatMap operators give us a lot of flexibility to handle events. We can merge them all together, track the most recently emitted one, track the first one and ignore other events until it’s done, or track one at a time and buffer other events in a queue for later use. What else could you want?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5764e6c2018c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrying a Network Request Despite Having an Invalid Token]]></title>
            <link>https://danielt1263.medium.com/retrying-a-network-request-despite-having-an-invalid-token-b8b89340d29?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b89340d29</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[rxswift]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 01:19:28 GMT</pubDate>
            <atom:updated>2020-05-23T20:43:55.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*4EcmICKo4Y-fArilgTFY7w.png" /><figcaption>Never see a 401 error again.</figcaption></figure><h3>RxSwift and Handling Invalid Tokens</h3><p>I was recently asked to help with creating a system that would reauthorize a user when a 401 was encountered during a network request. After reauthorizing the user, it should retry the request with the new token. Because the word “retry” was used, I immediately thought of the `retry` operator, but in retrospect it might have been better to use `catchError`… That said, here is what I ended up with and my thought process while developing it.</p><p>First I roughed out what I need:</p><ol><li>Since URLRequests will potentially need to be created with new tokens, I need a function that can create a request when given a token.</li><li>Since retryWhen provides an Observable&lt;Error&gt; that emits every error the stream throws, I need a function that will refresh the token and emit a trigger event on unauthorized errors while passing all other errors down the line.</li><li>Since multiple requests could be unauthorized while the service is waiting for a new token, I need a way to notify all the requests once the token is provided.</li></ol><p>Lastly, since this is going to be a pretty complex job, I need to make sure I can test it without involving the network.</p><p>Because of requirement (3) I know that there will have to be some sort of object that can bind all the requests together and this object is primarally in charge of acquiring new tokens when needed. I’ll name it’s class TokenAcquisitionService. This object will also provide the most recent token on request.</p><p>With all of the above information. I can expect a function definition like this:</p><pre>/**<br> Builds and makes network requests using the token provided by the <br>     service. Will request a new token and retry if the result is an <br>     unauthorized (401) error.</pre><pre> - parameter response: A function that sends requests to the network <br>     and emits responses. Can be for example <br>     `URLSession.shared.rx.response`<br> - parameter tokenAcquisitionService: The object responsible for <br>     tracking the auth token. All requests should use the same <br>     object.<br> - parameter request: A function that can build the request when <br>     given a token.<br> - returns: response of a guaranteed authorized network request.<br> **/<br>typealias Response = (URLRequst) -&gt; Observable&lt;(response: HTTPURLResponse, data: Data)&gt;<br>typealias Request = (String) -&gt; URLRequest</pre><pre>func getData(response: <a href="http://twitter.com/escaping">@escaping</a> Response, tokenAcquisitionService: TokenAcquisitionService, request: <a href="http://twitter.com/escaping">@escaping</a> Request) -&gt; Observable&lt;(response: HTTPURLResponse, data: Data)&gt; {<br>    return Observable<br>        .deferred { tokenAcquisitionService.token.take(1) }<br>        .map { request($0) }<br>        .flatMap { response($0) }<br>        .map { response in<br>            guard response.response.statusCode != 401 else { throw ResponseError.unauthorized }<br>            return response<br>        }<br>        .retryWhen { $0.renewToken(with: tokenAcquisitionService) }<br>}</pre><p>As you can see above, code isn’t pretty when it’s in a Medium post. <a href="https://gist.github.com/danielt1263/68097ac187cd43c23945bc6c15f5cc0b">The RetryingTokenNetworkService code can be found here.</a></p><p>An explanation of the above function is as follows:</p><ul><li>.deferred { tokenAcquisitionService.token.take(1) } will subscribe to, and pass on, the token emitted by the service whenever this observable is subscribed to. In effect, when the request is started and whenever it is retried, this line will get the latest token from the service.</li><li>.map { request($0) } will build the request with the token provided.</li><li>.flatMap { response($0) } will send the network request and wait for the response.</li><li>guard response.response.statusCode != 401 else { throw ResponseError.unauthorized } will cause the observable to emit an error if the response was rejected for being unauthorized.</li><li>.retryWhen { $0.renewToken(with: tokenAcquisitionService) } will give the service a chance to handle the .unauthorized error, but pass on any other error.</li></ul><p>You can use the above function with any network layer you care to name, whether that’s Alamofire, URLSession or whatever, as long as the layer allows the creation of the (URLRequest) -&gt; Observable&lt;(response: HTTPURLResponse, data: Data)&gt; function. Because I used a function definition here instead of tying my code to a particular service, it can be used with any of them and allows for easier testing.</p><p>The TokenAcquisitionService itself consists of two functions and a property (along with some private properties.) The code in the gist above has doc comments so I will just explain how they work here rather than what they do. Be sure to read the doc comments in the gist before you continue with the below.</p><h3>func trackErrors(for:)</h3><p>In this method, I start with the source object as an observable.</p><ul><li>guard (error as? ResponseError) == .unauthorized else { throw error} will throw any error other than the one it is watching for. The idea is that if something else goes wrong, the calling code would want to know. An .unauthorized error will cause a next event to emit.</li><li>do(onNext:) The block handed to this operator will send a next event to the private Subject that handles the chain which gets a new token. This is run through a subject because all the network requests that need to retry must be merged together so they can all be notified once the new token is acquired. The recursive lock guards the subject against events from different threads.</li><li>filter { _ in false } eats all the next events emitted by the chain. This is because we don’t want to trigger a retry until after the new token has been acquired, but we still want to pass on any stop events (completed or an error other than an unauthorized network request.)</li><li>Observable.merge(token.skip(1).map { _ in }, error) Remember that subscriptions to token will immediately receive a next event but this is unnecessary because we already know that the current token is invalid. We want the trigger for the <em>next</em> token. We also want all the stop events from the error observable (remember, this observable won’t emit next events.</li></ul><h3>init(initialToken:getToken:extractToken:)</h3><p>In here is the code that actually refreshes the token. Keep in mind that this is the code that all unauthorized network requests will be subscribed to, as well as any streams that want to know what the current token is and when it changes.</p><ul><li>relay.flatMapFirst { getToken() } is the line that requests a new token and makes sure that only one request is made for each batch of unauthorized requests that are waiting.</li><li>guard urlResponse.response.statusCode / 100 == 2 else { throw ResponseError.refusedToken(response: urlResponse.response, data: urlResponse.data) } will inform all listening requests that the service was unable to successfully extract a token, otherwise it will extract the token and emit it.</li><li>startWith(initialToken) ensures that the token property is pre-loaded with a value.</li><li>share(replay: 1) ensures that any observers that subscribe to the token property will immediately get the most recently acquired token value so they can attempt the first request.</li></ul><h3>FAQ:</h3><p>What if I have to display a login screen in order to get a new auth token?</p><p>You could do that inside the getToken function that is passed into the service. It could even make a get token request with the server and if that fails, present a screen to the user and make another get token request. You could put a `retry(3)` in there to give the user a few chances. On an ultimate failure you could either throw an error, or push out a response with a non-200 series status code (even a 401. If a 401 occurs during the getToken attempt the service will emit an error.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b89340d29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recipes for Combining Observables in RxSwift]]></title>
            <link>https://danielt1263.medium.com/recipes-for-combining-observables-in-rxswift-ec4f8157265f?source=rss-656abcc75dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec4f8157265f</guid>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[reactivex]]></category>
            <dc:creator><![CDATA[Daniel Tartaglia]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 22:17:16 GMT</pubDate>
            <atom:updated>2020-12-04T20:52:22.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Several operators exist to combine multiple observables into one. This document shows the basics of the various combining operators <em>and</em> shows some more advanced recipes using them.</p><h3>Combine Latest</h3><p>The combineLatest operator is used whenever you have two or more observables emitting values, and you want access to the latest value emitted from each of them whenever one of them emits a new value. It can be used, for example, to combine a username and password to make a login request.</p><pre><strong>func</strong> example(username: Observable&lt;String&gt;, password: Observable&lt;String&gt;) {<br>    <strong>let</strong> credentials: Observable&lt;(String, String)&gt; = Observable.combineLatest(username, password)<br>    //...<br>}</pre><p>It also comes in handy when you have an array of Observables, and you want to convert them into an Observable that emits an array.</p><pre><strong>func</strong> example(imageObservables: [Observable&lt;UIImage&gt;]) {<br>    <strong>let</strong> images: Observable&lt;[UIImage]&gt; = Observable.combineLatest(imageObservables)<br>    //...<br>}</pre><p>Sometimes, one of the Observables will emit several values before all of them have. The combineLatest operator will ignore those values until such time as all the constituents have emitted a value. If you don&#39;t want to miss out on any such values, then it&#39;s best to use startWith to provide defaults:</p><pre><strong>func</strong> example(pageNumber: Observable&lt;Int&gt;, searchTerm: Observable&lt;String&gt;) {<br>    <strong>let</strong> pageAndTerm: Observable&lt;(Int, String)&gt; = Observable.combineLatest(pageNumber.startWith(1), searchTerm)<br>    //...<br>}</pre><p>On occasion you need to use a value emitted by an Observable to create a new Observable, but you want to tie the value with the new Observable. For this, you can use just to lift the value back up into an Observable and combine it:</p><pre><strong>func</strong> example(pageNumber: Observable&lt;Int&gt;) {<br>    <strong>let</strong> pageAndItems: Observable&lt;(Int, [Item])&gt; = pageNumber<br>        .flatMapLatest { page <strong>in<br>            </strong>Observable.combineLatest(Observable.just(page), getItems(forPage: page))<br>        }<br>}</pre><p>You could also do the above with an additional map:</p><pre><strong>func</strong> example(pageNumber: Observable&lt;Int&gt;) {<br>    let pageAndItems: Observable&lt;(Int, [Item])&gt; = pageNumber<br>        .flatMapLatest { page <strong>in</strong> <br>            getItems(forPage: page)<br>                .map { (page, $0) }<br>        }<br>}</pre><h3>Zip</h3><p>Then there are times where you want to fire off a bunch of Observables, then wait until they all emit a value. If you know they will all emit no more than one value, you <em>could</em> use combineLatest. However, it&#39;s probably more expressive of intent if you use zip.</p><pre><strong>func</strong> example(imageServerRequests requests: [Single&lt;Data&gt;]) {<br>    <strong>let</strong> images: Observable&lt;[Data]&gt; = Observable.zip(requests)<br>    //...<br>}</pre><p>The zip operator also comes in handy if an Observable is emitting values too fast and you want to slow it down. Normally, from will emit all of the values in the array immediately upon subscription; by zipping it with an Observable that emits its values slowly, you can force from to slow down.</p><pre><strong>func</strong> example(imageURLs: [URL]) {<br>    <strong>let</strong> values: Observable&lt;URL&gt; = Observable.zip(Observable.from(imageURLs), Observable.interval(3, scheduler: MainScheduler.instance), resultSelector: { $0 })<br>    //...<br>}</pre><h3>Merge</h3><p>There are times when you have data coming from several possible sources and you want to treat it all the same; this is especially true with Void Observables which act as action triggers. For this merge is a great choice.</p><pre><strong>func</strong> example(pullToRefresh: Observable&lt;Void&gt;, tapToRefresh: Observable&lt;Void&gt;) {<br>    <strong>let</strong> refresh: Observable&lt;Void&gt; = Observable.merge(pullToRefresh, tapToRefresh)<br>    // ...<br>}</pre><p>Another common use of merge is when you have Observables that perform different actions on the same (usually) piece of state. In these cases you don&#39;t exactly want to combine the emissions, rather you need them to come through one at a time, but you need to distinguish between them.</p><pre><strong>func</strong> example(startOver: Observable&lt;Void&gt;, nextPage: Observable&lt;Void&gt;) {<br>    <strong>enum</strong> Action {<br>        <strong>case</strong> startOver<br>        <strong>case</strong> nextPage<br>    }</pre><pre><strong>let</strong> action: Observable&lt;Action&gt; = Observable.merge(startOver.map { .startOver }, nextPage.map { .nextPage })<br>}</pre><h3>WithLatestFrom</h3><p>Sometimes you want to combine observables, but you only want an event when one of them fires, not both. In that case, you use withLatestFrom(_:_:).</p><pre>let selectedFamilyMember = input.selectedIndex<br>    .withLatestFrom(familyMembers) { $1[$0.row] }</pre><p>There is also a withLatestFrom(_:) that will give you the latest emission of the second observable and ignore the emission from the first observable. That version is great for triggers and is the one that is most commonly used.</p><h3>Concat</h3><p>Lastly, there are times when you want to fire off a bunch of Observables in sequence rather than all at once, but you still want to collect up all the results. The concat operator is good for that.</p><pre>let results = Observable.concat(networkRequests)</pre><p>This will cause all the Observables in the networkRequests array to be subscribed to one at a time. The next one in the sequence won’t be subscribed to until the previous one completes. Make sure that the inner observables emit completion events or it will never finish.</p><p>Another great source to get a sence of how these operators work is in the <a href="https://github.com/ReactiveX/RxSwift/blob/master/Rx.playground/Pages/Combining_Operators.xcplaygroundpage/Contents.swift">Combining_Operators</a> playground. Always be sure to check the official docs when you have any questions about an operator. Every one of them is well documented both as a doc comment and within a playground.</p><p>I hope this little tour of the combining operators helps out. If I got anything wrong, or your have better, or other, examples then by all means send me a DM on slack, twitter or reddit (danielt1263) or just leave a comment here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4f8157265f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>