Practical MVVM + RxSwift

App main view

UI Setup

Child View Controllers

View Model Setup

Basic View Model Architecture

Adding RxSwift

  1. Loading(Bool): Whereas we send a request to the server, we should show a loading. So the user understands, something is loading now. For this, we need the Observables of Bool. When it was true it would mean that it is loading and when it was false — it has loaded (if you don’t know what are observables read part1).
  2. Error(homeError): The possible errors from the server and any other errors. It could be pop ups, Internet errors, and … this one should be observables of error type, so that if it had a value, we would show it on the screen.
  3. The collection and table views data ,…

UI to data binding (RxCocoa)

  1. First, we wrote an extension to Reactive which is in RxCocoa and affect RX property of UIViewController.
  2. We implement isAnimating variable to UIViewControllers of type Binder<Bool> so that can be bindable.
  3. Next, we create Binder and for the binder part, the closure giving us the view controller (vc) and the value of isAnimating (active). So we are able to say what happens to the viewController in each value of isAnimating, so if active is true, we are showing loading animation with vc.startAnimating() and hide the loading when active is false.

Last touch

Connect Albums and Tracks properties

Request data from View Model

  1. we are emitting loading value to true and because we already do the binding in HomeVC class, our viewController now showing the loading animation.
  2. Next, we are just sending a request for data to the network layer (Alamofire or any network layer you have).
  3. After that, we got the response from the server we should end the loading animation by emitting false to loading.
  4. line (13–19) Now having the response of the server, if we got into trouble, we emit the error value. Again, because the HomeVC has already subscribed to errors, they are shown to the user.
  5. (line 8–11) If the response was successful, we parse the data and emit values of albums and tracks.

Adding bonus animation

live demo

Final words.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store