Michael Long
2 min readAug 18, 2019

--

Nice “pure” approach to RxSwift and VM’s, but it comes with a few caveats and drawbacks:

The foremost of which is that it boils everything down into a single, somewhat massive initialization function that can be somewhat difficult for a reader to parse and understand.

It’s “possible” to break out some of the functionality into separate methods/functions to combat this, but that can be somewhat tricky in practice if you attempt to access “self” before everything is initialized on the VM. Your later example gets around this with the function returning a super tuple, but at the expense of some added boilerplate where, for example, validatedUsername is defined as a function return value, assigned as a temp value, and then mentioned yet again in the actual function return.

In fact, this is about the maximum level of complexity I’d tolerate before wanting functionality broken out into more discrete, easily understood methods. (Swiftlint would be complaining too.)

The “You must be very careful to not use instance mthods inside closures.” rule is more of a guideline than a rule, really. ;) Weak/Unowned are tools to be understood, not avoided.

It’s true that fileprivate functions can combat this, but it assumes that said functions are pure and have no dependencies on other data in the VM. In fact, your configureImageURLs example is only possible because that function has a hidden dependency on a global static variable. In effect you’ve done a tradeoff against a “possible” memory leak as opposed to tighter — and completely static — coupling within the app.

The static dependency now effectively precludes any testing of of the function using mock data, not that it’s testable anyway as it’s a completely hidden fileprivate function. Effectively a double-whammy.

Finally, I might add that this methodology is only suitable to an RxSwift/UIKit project. You won’t, for example, be able to do the same thing with Combine/SwiftUI as there’s no way to get the input stream beforehand. You have to have the state/bindings to bind to the declarations before the declarations actually construct the interface.

Anyway, just some food for thought.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

No responses yet