Skip to content

Instantly share code, notes, and snippets.

@gorozco58
Last active January 13, 2017 20:04
Show Gist options
  • Save gorozco58/655327edb40b628dba8a4fd5d2b904b8 to your computer and use it in GitHub Desktop.
Save gorozco58/655327edb40b628dba8a4fd5d2b904b8 to your computer and use it in GitHub Desktop.
import UIKit
import RxCocoa
import RxSwift
class MainViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
fileprivate let disposeBag = DisposeBag()
fileprivate let viewModel: RepositoryViewModelType
init(viewModel: RepositoryViewModelType) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//searchbar observable
var searchBarText: Observable<String> {
return searchBar
.rx
.text
.map { $0! }
.filter { $0.characters.count > 0 }
.throttle(1, scheduler: MainScheduler.instance)
.distinctUntilChanged()
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
}
//MARK: - Private
extension MainViewController {
fileprivate func setup() {
tableView.register(UINib(nibName: String(describing: RepositoryCell.self), bundle: nil), forCellReuseIdentifier: String(describing: RepositoryCell.self))
viewModel
.fetchRepositories(for: searchBarText) //view model method to fetch the repositories that returns a Driver
.map { result -> [Repository] in //Map the response and handle an error if exists
switch result {
case .success(let repositories):
return repositories
case .failure(let error):
print(error.localizedDescription)
return []
}
}
//bind the response to the table view using a drive method
.drive(tableView.rx.items(cellIdentifier: String(describing: RepositoryCell.self), cellType: RepositoryCell.self)) { row, repository, cell in
cell.titleLabel.text = repository.name
}
.addDisposableTo(disposeBag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment