Skip to content

Instantly share code, notes, and snippets.

@ahernandezlopez
Last active October 25, 2017 06:58
Show Gist options
  • Save ahernandezlopez/3cbf72119dcb9868fcbcc0637661888d to your computer and use it in GitHub Desktop.
Save ahernandezlopez/3cbf72119dcb9868fcbcc0637661888d to your computer and use it in GitHub Desktop.
Example of implementation of Domain Events in Swift. The snippet illustrates Domain Events in a Service with RxSwift
import RxSwift
import UIKit
class ListingListViewController: UIViewController {
let contentView: ListingListView
let service: ListingService
let disposeBag: DisposeBag
init(service: ListingService) {
self.contentView = ListingListView()
self.service = service
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
contentView.frame = view.frame
view.addSubview(contentView)
// ...
let params = ListingServiceSearchParams()
service.search(params: params) { [weak self] result in
guard let listings = result.data else { return }
self?.contentView.listings = listings
}
service.events.subscribe(onNext: { [weak self] event in
guard let `self` = self else { return }
switch event {
case let .create(listing):
self.contentView.create(listing: listing)
case let .update(listing):
self.contentView.update(listing: listing)
case let .delete(listing):
self.contentView.delete(listing: listing)
}
}, onError: { error in
}, onCompleted: {
}, onDisposed: {
}).disposed(by: disposeBag)
// ...
}
}
class ListingListView: UIView, UITableViewDataSource, UITableViewDelegate {
private let tableView = UITableView()
var listings: [Listing] = [] {
didSet {
tableView.reloadData()
}
}
// ...
func create(listing: Listing) {
tableView.beginUpdates()
defer { tableView.endUpdates() }
listings.append(listing)
guard let indexPath = indexPathFor(listing: listing) else { return }
tableView.insertRows(at: [indexPath], with: .automatic)
}
func update(listing: Listing) {
guard let indexPath = indexPathFor(listing: listing) else { return }
listings[indexPath.row] = listing
tableView.reloadRows(at: [indexPath], with: .automatic)
}
func delete(listing: Listing) {
tableView.beginUpdates()
defer { tableView.endUpdates() }
guard let indexPath = indexPathFor(listing: listing) else { return }
listings.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment