Swift 3, keep realm out of appdelegate

278 Views Asked by At

I'm working with the VIPER architecture in my app, now I want to use my realm database. However, normally I would put it in AppDelegate, if I then would want to use it in the ListInteractor, I need to import UIKit which is against VIPER rules.

How could I solve this nicely? I've considered the following options:

  • Creating a service
  • A singleton solution
  • Just using import RealmSwift in the interactor, however, I would lose easy migration functionality.

I do want to be able to keep migrations as easy as possible, as well as other configs.

1

There are 1 best solutions below

0
On
  • You would utilize the Realm API entirely within Interactor zone (without UIKit's AppDelegate). The completion of a Realm asynchronous operation would then be converted to your own app-domain representation, perhaps even a (new?) entity over in entity zone. Regardless, all inter-zone messaging in VIPER is via app-domain constructs, not Realm constructs and not Apple-OS-framework constructs.
  • You would pick an inter-zone effects-framework that is your designated app-domain reactive way of representing flows of effects. In Swift, the 2 most likely choices are: RxSwift or Apple's Combine (or even OpenCombine if it is mature enough to support your needs). There are a few other choices too (ReactiveSwift, rolling your own), but one needs to know precisely why that one is choosing which one. Although you might peek at RxCocoa's implementation to beg, borrow, swipe, & mimic ideas, you would strictly refrain from utilizing any of RxCocoa itself inter-zone among the view, interactor, presenter, and router zones. You would design your own app-domain usage of RxSwift (in ways that vaguely resemble RxCocoa's adaptation of Apple frameworks into RxSwift) without RxCocoa leaking any Apple-OS-framework constructs into the inter-zone reactive effects-flow messaging.
  • Then all inter-zone messaging between the view, interactor, presenter, and router zones is via your chosen effects-flow framework using your app-domain representation of what event is transpiring (without reference to Realm or to Apple-OS frameworks/contructs/concepts) when crossing VIPER zone boundaries. This quarantining intra-zone for forthcoming-future swapability is what makes VIPER a Clean architecture, so that Realm can be jettisoned (in some port of your app to a different environment or for a better replacement of Realm someday) and so that iOS frameworks can be jettisoned (in some MacOS port of your app someday, or vice versa, or even in some Android or UWP port of your app someday).
  • By relying on a designated reactive effect-flow library/framework in your inter-zone app-domain-centric messaging, you will not be tempted to utilize UIKit's AppDeleglate for any inter-zone messaging as you were in OP. This answer is in effect drastically expounding on what the reactive interpretation of “creating a service” would look like.