Hello! I’m sure most of you have encountered at least one view controller that was so huge you couldn’t even search for what you wanted.

Or worse, you might have found that most controllers that have a tableView (or a collection, anything that has a data source) do the same… get the data, modify the data, update the view, repeat…

We do this all the time, and if you do everything inside each view controller, they probably are 0% reusables.

Diagram

This is the diagram we’ll follow for a normal table view controller:

TableViewController asks dataSource for data.

asks for data. dataSource has an adapter that binds our tableView to our data.

has an that our to our data. The adapter has an observable array of elements, so when it gets updated the adapter gets notified and the tableView updates accordingly.

Note: I’m not using any external libraries for this.

Observable

First, our observable collection will basically follow this protocol:

ObservableCollection protocol

From here, you can guess that there will be an action ( ObserverAction ) for 'everything' we do with our collection (append, remove, etc), hence the observers, which will be there to bind the actions.

I made a simple observable for an array, ObservableArray<T> , which is the one we'll use for this example (the class and whole project is linked at the end).

Why an observable? Look how easy is to add some observers for everything we do with it:

Adapter — Binding the view to our data

Next thing is create our adapter, which can conform to:

public protocol ComponentAdapter {

associatedtype Component: UIView

associatedtype Elements: Collection

}

We can create a TableViewAdapter conforming to this protocol. In that case the Component will be a UITableView .

Basically we have our view and the data we want to bind it to.

The process of binding is super easy with our observable array. In the init method of our adapter you can do something like:

How our data can be bound to the component using an ObservableArray in an Adapter class

DataSource

The table view controller will be bound to a data source, a custom one conforming to UITableViewDataSource that has an adapter to manage the updates in our data, at the source and UI level.

Inside the custom data source, we use our tableViewAdapter

Inside, we implement the typical methods: numberOfRowsInSection , cellForRowAt indexPath and maybe others to delete a cell by swiping it or just move a row to other position. For example this is the whole code to move a row:

Code inside our data source to move a row

Easy, right? With our adapter and observable our code gets sooo thin and elegant 😁

Our HUUGE (😉) view controller:

That’s it! A very tiny view controller fully responsive and ready to be used as desired.

Thanks for reading!

Below you will find the flowchart and a repository with a complete usage example of these classes.

Links