QuickToDo CoreData + Rx + MVVM (Part 2)

Rx + MVVM

Bratislav Ljubisic
3 min readJun 24, 2019
Frankfurt Hauptbahnhof

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:

Storage outputs protocol

That observable is implemented as PublishSubject in CoreDataModel.swift.

Outputs implementation 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:

Core Data fetched items

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:

ViewModel subscription to Model output

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>:

Model returns Observable

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Bratislav Ljubisic
Bratislav Ljubisic

Written by Bratislav Ljubisic

Father of two and iOS developer in spare time

No responses yet

Write a response