The education of Paul Weichhart

Write like nobody is reading

MVVM with SwiftUI and Combine

Since I first read about the architectural pattern MVVM in Ash Furrow’s fantastic Book “Functional Reactive Programming on iOS”, I got struck by the Design. I really liked the separation of concerns, the promise of small independent layers & the possibility to easily test the ViewModel. Since then I researched this topic, read several Articles and studied different Repositories how to bring this pattern to iOS (also by the Inventor and Microsoft Developer Josh Smith).

While you can easily create a ViewModel & move much of the Views responsibility to a separate level, the binding of each Layer is the key concept of this Architecture. I experimented with a Closure based approach and several Reactive Libraries like ReactiveCocoa, ReactiveSwift & RxSwift in the past, however these Libraries only bring the Concept of “A Stream of values over time” to iOS. Pretty soon you will find yourself introducing several new Libraries that wrap Apple Frameworks — Networking or CoreData for example. This changed however with the introduction of Combine and SwiftUI at WWDC 2019.

Getting Started with Combine

Since its introduction I wanted to write about MVVM and after finishing Donny Wals awesome Book “Practical Combine” I was finally able to create an Example. The App simply fetches & renders a List of 5 Shares. The Textfield enables searching the List for available Shares.

I tried to implement the following key features:

  • Moving all of the View’s logic & State into the ViewModel
  • Avoid using Never and handle Errors accordingly in the View
  • Create a separate NetworkLayer that fetches & decodes the Model
  • Make small reusable Views

Show me the Code

The following Example uses some new features that are currently only available with the Xcode 12 Beta.

Something to add or like to know? Drop me 280 characters on twitter @paulweichhart