Swift structs, closures and Memory Leaks

Using structs and registering closures with a framework? Did you know closures are reference types?

If your closure is registered with a class from a framework and the closure is closing over self then you have a strong reference cycle memory issue. For example, let’s say we have a struct which has an RxSwift class Variable<String> member called someVariable.

When you give the subscribeNext the closure, it will store that closure into the framework. In other words, it has a reference to the closure. If you are referring to self in that closure, you have a strong reference cycle. The struct has a Variable which has a closure that has a reference back to the struct.

Can we just make the self reference a weak reference? No. Not if it’s a struct.

If it’s a class, we can do the following:

Note that we are using class and [weak self] now. We also took away the mutating from before the function.

That solves the memory issue! Thanks goes to some helpful humans which include Darren and Marc Khadpe in this Stackoverflow post.

Update: For an example such as this, Carlos García rightfully pointed out that using [unowned self] would be better. It’s faster and more. Carlos pointed out this article: How Swift Implements Unowned and Weak References and a related Twitter thread.

If you are going to use unowned, you will want to know when your app can crash when using it.  “Weak, Strong, Unowned, Oh My!” – A Guide to References in Swift is a good guide for when to use weak, unowned, and the default strong references.

Swift Protocols With Associated Types – PATs

What first led me into understanding Protocols With Associated Types (PATs)? Answer: RxSwift. It’s an awesome FRP framework for Swift.

What led me to the protocol compilation error “..can only be used as a generic constraint” which looks like this?

1PAT with compiler error

(Source: Alexis Gallagher – Protocols with Associated Types – 1:24)

Answer: Applying BDD (Behavior-Driven Development) to our Protocol Oriented MVVM RxSwift empowered code and using dependency injection.

We were going to use structs and protocols wherever we could. However, we had to back off some. Thanks to Alexis Gallagher, it’s clear now why we ran into the same problem that he presented in his video presentation, Protocols with Associated Types and how they got that way (maybe). Here’s a problem example he shows:

2PAT single variable declaration

(Same source: 2:47)

This great presentation was part of the 2015 Functional Swift Conference. The Protocols with Associated Types, and How They Got That Way slides are available. However, I highly recommend listening to the whole presentation. Since it’s 56 minutes long, this blog post links to certain key parts of it with associated snapshot images just to give you a taste of what is in there.

From this presentation, there are some crucial key takeaways:

  • Can’t use dynamic dispatch with PATs
  • typealias can do two very different things
  • There are workarounds if you need to do dynamic dispatch

Can’t Use Dynamic Dispatch With PATs

The compilation error “..can only be used as a generic constraint” described above shows how PATs are unique and different from plain old Protocols. The following dives into the ramifications of this situation:

3No Dynamic dispatch

(Same source: 6:54)

PATs are their own thing. As Alexis G. says, call them PATs and recognize how they are different.

typealias Can Do Two Very Different Things

4typealias two different uses

(Same source: 11:39)

As specified in the Swift Language Reference on Declarations, you can use typealias to:

  • Create a name for a type. See the “Type Alias Declaration” section.
  • Require something that conforms to a PAT, to specify a type. See the “Protocol Associated Type Declaration” section

Slide 18 of his presentation has a good example of showing typealias being used in a PAT.

There Are Workarounds If You need to do Dynamic Dispatch

11HowToLovePATs

(Same source: 39:08)

Workarounds are:

  • Enums
  • Type Erasure

The future looks bright if they add Existentials to the language. There is a Stackoverflow post about the generic concept an Existential Type.

Summary

Until they add Existential Types to the Swift language, we should fully understand PATs and how to use other parts of the Swift language to accomplish what we want.

As an aside: If you got this far, you really may want to watch the whole presentation on youtube. This blog post was made to just catch some of the interesting bits for later referral. Enjoy!

RxSwift Driver – What is it?

Curiosity is a powerful thing. When I saw this RxSwift Driver being discussed on RxSwift Slack and read the helpful RxSwift GitHub issue “Need better explanation / examples for Driver” submitted by Florent Pillet, it seemed helpful to capture what I saw.

As Carlos García shared on the GitHub issue:

One should think of the following:

as the same as:

Krunoslav Zaher aka kzaher on the RxSwift slack community said that it is a combination of: “main thread + shared subscriptions + no errors.” He goes on to say that shareReplay(1) is a shared subscriptions example. Carlos adds there are several examples in RxExample.

kzaher sums it all up nicely by sharing:

Yeah, it’s just a tiny builder/dsl for Observables. I think this should help me and others a lot with ensuring you can safely bind values to UI.

Using Driver is optional, but it helps the compiler catch things and will help emphasize things that might have been missed. As kzaher put it:

..and warn me when I’ve forgot to handle unexpected errors, or binding from background thread or doing something I should have when dealing with UI applications.

You may want to keep an eye on the RxSwift documentation as it grows and develops over time. Specifically, this Units document. Driver sounds exciting and I look forward to trying it in-depth in the near future!

Jan 2, 2016 Update: The Units document has been updated and much more has been added to it. Good stuff!

RxSwift Glossary and Concepts

Do you speak RxSwift? Do you know the concepts, words and operators? Here is a snapshot summary of many of them.

Some of the RxSwift Concepts from Getting Started

An Observable is a definition of: 

  • “..how the sequence is generated..”
  • “..what parameters are used for element generation..”

Disposing

“..release all of the resources that were allocated to compute upcoming elements..”

Observable aka Sequence

  • One after another, the Observable sends a Next (element), Error, or a Completed
  • What stops them from coming? An Error, Completed or dispose the subscriptions.

Observer

Subscribes to Observables

Subject

(Source: Rx.playground)

Terse mode: “acts both as an Observer and as an Observable”

Full mode: “A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.”

Operators

There is a list sorted by functionality at https://github.com/ReactiveX/RxSwift/blob/master/Documentation/API.md#rxswift-supported-operators

Operator Types:

(Sources: Rx.playground and github docs)

  • Combination operators – startWithcombineLatestmergeswitchLatestzip; “Operators that work with multiple source Observables to create a single Observable”
  • Conditional and Boolean Operators – takeUntiltakeWhile – “Operators that evaluate one or more Observables or items emitted by Observables.”
  • Connectable Observable Operators – multicastreplay, replayAll, publish – “like an ordinary Observable yet only when its connect() is called does it emit”
  • Error Handling Operators- catchErrorretry – “Operators that help to recover from error notifications from an Observable.”
  • Filtering Observables – distinctUntilChanged, filtertake; “Operators that selectively emit items from a source Observable.”
  • Mathematical and Aggregate Operators – concat, reduce – “Operators that operate on the entire sequence of items emitted by an Observable”
  • Observable Utility Operators – doOn, subscribesubscribeNextsubscribeCompletedsubscribeError; “toolbox of useful Operators for working with Observables”
  • Transforming Observables – map / selectflatMapscan; “Operators that transform items that are emitted by an Observable”
  • Units – “purpose of Driver unit is to ensure the underlying observable sequence has the following properties”: It “can’t fail”, “main thread”, and more.

Schedulers

Schedulers are an abstraction away from what does work (queues / threads).

RxSwiftCommunity

By the way, the RxSwiftCommunity bears checking in on from time to time. Action is listed there and it comes up often in the RxSwift Slack community and at least once in Stack Overflow. Just like the adoption of RxSwift, I sense the community will grow over time.

Update: If one looks at the code commits done for the RxSwiftCommunity website, one can easily see lots of activity going on.

RxSwift and Memory

Tom Burns asked a good question about TableView bindings outliving the view controller. As he said:

I’m asking because I noticed that some of my tableview bindings were outliving the view controller being popped back off the stack and it seemed like unnecessary work was being done…

kzaher of the RxSwift Slack community pointed out the following code as being the culprit:

Tom fixed the code to use an “[unowned self]” before the newObjects. Such as:

Although such memory situations aren’t limited to RxSwift, using RxSwift might encourage such situations to come up more often. It something to watch out for.

Regardless, this is something we all can run into from time to time. I feel fortunate enough to have caught the conversation in the RxSwift Slack community and am grateful to Tom for asking.

Simpler RxSwift Test Code

Looking at some RxSwift test code, I knew it could be better. As I shared with Krunoslav Zaher aka kzaher in the RxSwift Slack community:

I feel the opportunity for improvement down to my soul.

Test Code
He kindly helped me simplify some RxSwift test code. He suggested that instead of:

Do something like this:

To make that work, I had to change the oldBakeryServiceSpy from something like this:

To this:

This also allowed us to use failWith. As in:

 

More kzaher Words of Wisdom

if you are mocking, just use just, sequenceOf, [].toObservable()

It was also shared that TestScheduler will be released soon and one can look at the unit tests.

What about Simplifying Our Use of the DisposeBag?

As a result of what we read in the README, we use DisposeBag objects often. As kzaher shared:

If you use operators, that will reduce the amount of dispose bags significantly. We handle all of disposing for you. You only dispose terminal endpoints where you do “subscribe”

All Part of the Game of Learning

Slowly things are improving. Although it’s all part of the game of learning something new, I think it would serve all well if someone created a game called “Simplify This RxSwift code.” I know I would happily play it.

Path to Learning FRP and RxSwift In a Nutshell

This is some of what I did to learn FRP / RxSwift:

The RxSwift Slack Community is awesome: http://slack.rxswift.org They guided me to these resources.

Besides playing around with lots of code, that’s the meat of what I did. I know every individual has his or her own path of learning. However, I figured I would share a terse version of mine in case it helps.

Update December 31, 2015: I would watch Functional Reactive Programming with RxSwift by Max Alexander first.

 

Learning RxSwift

Although ReactiveCocoa looked promising, it had a few things that are not yet there. These are outlined in an earlier article, ReactiveCocoa and MVVM Initial Experience. So, it was time to explore RxSwift.

I started with reading the concepts in the README. It was pretty straight forward. My next move was to find an example which is like the ReactiveCocoa oriented ReactiveTwitterSearch example that I loved so much. Where to begin? Good thing I discovered the RxSwift slack community.

Having an active slack community is a huge win! With the help of Carlos García in slack, I found GitHubSignup in the RxExample examples. This was definitely what I was looking for.

For fun, I created a small demo app which explored the bindings. I decided to see what was there for a UIPickerView and UITextView.

Compared to ReactiveCocoa, the RxSwift repo comes with extensions to some of the UIKit components. These are known as RxCocoa extensions. RxCocoa is located alongside the RxSwift code in the GitHub repository. However, if you are using CocoaPods like I am, RxSwift and RxCocoa are two separate pods.

After much searching, I discovered there is no extension made for the UIPickerView. So, I just made a PickerViewAdapter which contains a selectedPerson RxSwift Variable and PickingPersonViewModel. The adapter handles the UIPickerViewDelegate and UIPickerViewDataSource while calling through to the PickingPersonViewModel. The adapter is used by the View Controller.

With the UITextView, I had much better luck. With a simple binding, I was able to hook up a notes UITextView up with a specific note in the NotesViewModel. Changes to the UITextView would be reflected in the note. Pretty neat! Code is here:

_ = notesTextView.rx_text.subscribeNext { someText in

// Changes to notesTextView’s text triggers this block.

self.notesViewModel.currentNote().value.text = someText

}

How do extensions like rx_text work? I looked at the simplest example, the RxSwift UILabel extension. AnyObserver has an observer which is an event handler. As can be seen in the code, the UILabel extension with rx_text is an adapter that handles String events.

Although it’s currently Beta, there’s a sense that RxSwift will be out of beta soon. This is based on a Github request for it to be released as 2.0.0.

Based upon my observations and discussing it with some smart people at CARFAX I know, it looks like RxSwift is pretty solid. If you are interested in supporting MVVM in a Functional Reactive programming style, I recommend you check it out!

ReactiveCocoa and MVVM Initial Experience

The vision of Functional Reactive Programming (FRP) and specifically ReactiveCococa (RAC) 4.0 alpha are both impressive. FRP via RAC and Swift feels right. As mentioned in my previous article, RAC 4.0 is useable. Its core concepts are quite solid. Yet, one has to really want to dive in and be willing to offset any UIKit shortcomings. That’s fair since RAC 4.0 is alpha.

Where ReactiveCocoa needs more help:

  • There is a need for the ReactiveCocoa CocoaPods spec to be updated
  • There is a need for more UIKit extensions

Need for Updated ReactiveCocoa CocoaPods spec

That’s probably easy for one to do since it’s an update to an existing pod spec. If one doesn’t have time or want to, one can use Carthage as mentioned in my previous article, Swift 2 ReactiveCocoa MVVM Quest.

More UIKit Extensions

Based on a post here by Neil Pankey (a collaborator on ReactiveCocoa), Rex is a ReactiveCocoa Extensions project that eventually will get merged into ReactiveCocoa. As Neil mentions:

It’s not there yet, because “..haven’t found the time to port them, flush out the missing properties, add documentation, etc”

Although it has some extensions, more are needed. I immediately came up for the need for an extension that would let me capture text in a UITextField. Digging deeper I see in a somewhat older post, that there are many extensions that need to be ported over to Swift. Looking at Rex UIKit specific code myself, I think that’s still the case. If the community rallies around making more UIKit Extensions, it would help everyone.

To address what I needed now, I used a fork of ReactiveTwitterSearch originally made by Colin Eberhardt, and grabbed the UIKitExtensions code and a couple other items. Doing that, I was able to bind the text put into a text field straight into a View Model like so:

        loginViewModel.username <~ usernameTextField.rac_text

That line of code is quite similar to the awesome but dated article RAC 3 Properties section of MVVM with ReactiveCocoa 3.0.

So, that is neat and powerful since with some easy to read binding/configuration one is making it much easier to do MVVM. As long as you don’t mind, piecing things together and absorbing the learning curve, this power is yours for the taking now.

Swift 2 ReactiveCocoa MVVM Quest

The Quest

For a software developer (especially at CARFAX), the quest for cleaner code is worthy and eternal. In Swift and Objective-C, two main battlefields where clean code is threatened are View Controllers and client network code. View Controllers get big and client network code suffers from the Pyramid of Doom. The Pyramid of Doom is where there are many nested statements as shown in this Traditional asynchronous code slide. Following the advice of a smart friend named Mike Groner, I looked into ReactiveCocoa (RAC) and revisited MVVM.

Since we have looked at MVVM before and MVVM’s roots go way back to the Presentation Model via Martin Fowler, its concepts are not foreign. It’s true that one does not have to use RAC to do MVVM. As Natasha The Robot showed in her Swift Summit presentation and related Protocol-Oriented MVVM (POMVVM) article, one can manually follow the discipline of doing POMVVM without a framework. So, that’s great. One concern is that it requires the team to relentlessly apply discipline to do POMVVM well.

Shifting our attention to the Pyramid of Doom, how can RAC and Functional Reactive Programming in general help? To answer that question, I checked out Javier Soto‘s Back to the Futures Swift Summit presentation. It was eye opening. It discussed how we typically handle asynchronous callbacks (thus the Pyramid of Doom), error handling, and the concept of Futures as a way of getting rid of “…all the noise related to the asynchrony itself.” Easier to write, read and maintain code through Futures / Promises or better yet Signals sounds good! At the end of the talk, he also recommended ReactiveCocoa aka RAC.

So, What About ReactiveCocoa (RAC)?

OK. The message is loud and clear: Check out RAC! Natasha-The-Robot, guided me to Ash Furrow. Ash helpfully shared Functional Reactive Awesomeness With Swift So, RAC is impressive and RAC may even help one do MVVM. Which version of RAC should I investigate?

For an upcoming project, using Swift 2.1 is a no brainer. Can RAC or something similar be used in a Swift 2.1 project?  NachoSoto comes to the rescue on Twitter and Stackoverflow:  How to Add Production Ready ReactiveCocoa … Into Swift 2 iOS. So, the answer is yes!

Getting ReactiveCocoa 4.0

Being more than ready to dive into ReactiveCocoa 4.0, the question was now “how to get it?” I tried using CocoaPods, but the unofficial podspecs were out of date. it seems like a good answer is using Carthage with a Cartfile of:

github "ReactiveCocoa/ReactiveCocoa" "v4.0.0-alpha.3"

Since I have been a CocoaPods user, it didn’t immediately occur to me to copy the frameworks as per the RAC README page:

On the “General” tab of your application target’s settings, add ReactiveCocoa.framework and Result.framework to the “Embedded Binaries” section.

Success!

RAC and MVVM?

Could RAC or something like it also help with MVVM? Both my friend and Ash Furrow’s presentation above suggested that it could do so beautifully. Searching the web for the most recent ReactiveCocoa Swift examples, I found MVVM With ReactiveCocoa 3.0 by Colin Eberhart and Migrating to Swift 2 and ReactiveCocoa 4 by Martin Richter. So, it certainly seems so.

With ReactiveCocoa 4.0 and examples at hand, the journey has just begun and the quest for clean and well crafted code continues!