How RxSwift became a friend - with MVVM

Philipp Weiss
The Startup
Published in
2 min readMay 6, 2020

For almost 4 years I am using MVVM for the development of iOS Apps. Managing the communication by a bunch of delegate methods and closures always felt like a bit of a hassle — but I did not know what I was missing.

At some point I had to develop an app in Xamarin — also using MVVM. But there was one suprise. Using Visual Studio and its bindings it was… nice.

But back to Xcode! Here the problem remains. But there is a cure! 🙏

RxSwift & RxCocoa

Using it for Android development it is more or less state of the art. This was also the way I recognised there is a solution for the delegate and clousure mess.

Creating the ViewModel

BehaviourRelay: Stores your variable and can’t have an error. This is a very practical feature, since our UIView elements shouldn't get any errors. Please don’t misunderstand — errors that you want to show to the user will be converted to a BehaviourRelay as well, but the View itself shouldn't receive an error.

PublishRelay: Used to observe user interaction. Here it will be used to watch for a Button tap.

Driver: Also no errors and always on the main thread. This also means no more DispatchQueue.main closures or even worse forgetting to use it! If you create the driver from some object that can receive errors you will need to handle the error in the init method.

Creating the ViewController

Bind: Bind one rx resource to another. If the one changes the other will also change.

Drive: Like a binding it will change a value if the other changes but on the Main Thread.

DisposeBag: This will deinit all rx bindings and subscriptions after the disposebag released

RxExtension

With an extension it is possible to define your own binding / driver behaviour. In this case we will add an animation if the image is changed. This concept can be applied on every UIView element. So you can create your custom binding behaviour library.

The Result

Conclusion

With only 3 lines of ViewController code we can handle all the UI related behaviour. For me it is a true alternative to keep the ViewController simple and clean — even in a more complex use case.

So if you plan to use MVVM for an iOS App give it a try 🤙

--

--