How to fail miserably with RxSwift + MVVM

This episode of making fun of MVVM

I just love how MVVM devs never seem to be able to write something self-contained. In this episode I’m going to show how MVVM used view model to do view controller’s job, then used networking to do view model’s job, and ended up with RxSwift doing both of the jobs.

What you can tell from project structure

The concept of side effects

class PhotoListViewModel: PhotoListViewModelActions {
let imageLoaderService = StringImageLoader()
// MARK: - Variables
private
var currentPage = BehaviorRelay(value: 1)
private let photoService = PhotoService.shared
private let disposeBag = DisposeBag()
var photoList = BehaviorRelay<[PhotoListModel]>(value: [])
var imageDownloaded = PublishRelay<(Int, UIImage?)>()

init() {
self.fetchImages(currentPage: self.currentPage.value)
}
}
private let photoService = PhotoService.shared
private let disposeBag   = DisposeBag()
init() {
self.fetchImages(currentPage: self.currentPage.value)
}
let photoList = RemotePhotoList()photoList.fetch(currentPage).onSuccess {self.updateUI()}
// all data are in photoList, use it to update view

Tell me you don’t know how to work with UIKit without telling me

Now to one of the big selling points of RxSwift. Binding.

private func bindCollectionView() {
// MARK: Bind photoList to collectionView
viewModel.photoList
.filter({ !$0.isEmpty })
.bind(to: collectionView.rx
.items(cellIdentifier: PhotoCollectionViewCell.identifier,
cellType: PhotoCollectionViewCell.self)) { _, _, _ in}
.disposed(by: disposeBag)
}
let photoList = RemotePhotoList()photoList.fetch(currentPage).onSuccess {self.updateUI()}
// all data are in photoList, use it to update view
var photoList = [RemotePhoto]() { didSet {updateUI()} }// api call
api.photoList.post(params).onSuccess {data in self.photoList = process(data)}

Thy kind are all of a piece. Pillagers. Emboldened by the flame of ambitions.

Let’s summarize what we’ve learned so far.

--

--

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