QuickToDo CoreData + Rx + MVVM (Part 2)
Rx + MVVM

As written in first part, general architecture for this sample app is MVVM with RxSwift in Model and ViewModel layer. Communication between View and ViewModel is done in more traditional way, but that will be explained later. This way app is build in more simple way and is easily maintained. View section is kept at its minimal, and does not contain any logic to it. All logic stuff is in ViewModel and Model layers. Model layer is seen as a compact layer from ViewModel, and it only has one entry point to it. All specific modules, like Core Data or Cloud Kit are kept invisible for ViewModel or View. Internal communication within Model is also built around Rx. Because of that, in Storage Protocol you can see that it’s output is this:

That observable is implemented as PublishSubject in CoreDataModel.swift.

As you can see this observable will be subscribed on background thread. Within getItems() function, found Items are pumped into this observable:

ViewModel is effectively subscribed to this observable on Main thread, and with each new Item received it will add that item as new entry in Items array. This array is actually consumed by View and it is displayed as a TableView:

CompletionBlock in this case is nothing more than TableView reload so that new items can be seen on View. With all of this we now have perfectly workable example of to do list app, but I wanted to add a little complication to it, so it would not be that simple. I thought that it would be nice to have simple hints when you try to enter new items, maybe from the database of already used items. We already have in place what we need in the database schema, so now we just need to implement this. We will start from Model, getHints method returns Observable<String>:

This Observable is subscribed on background thread but observed on main thread. That means that it will try to run in background thread (which is a rule when dealing with CoreData or network access, eg. CloudKit), but it will return values on main thread which is needed as we will display those values on UI.