Skip to content

Instantly share code, notes, and snippets.

@gonzalezreal
Created June 12, 2016 19:27
Show Gist options
  • Save gonzalezreal/7bec88cafe765269a1df440c5fb88253 to your computer and use it in GitHub Desktop.
Save gonzalezreal/7bec88cafe765269a1df440c5fb88253 to your computer and use it in GitHub Desktop.
RxSwift slides – Code for the search sample
class SearchResultsViewController: UITableViewController {
// MARK: - Properties
private let viewModel: SearchResultsViewModelType
private let disposeBag = DisposeBag()
// MARK: - Initialization
init(viewModel: SearchResultsViewModelType = SearchResultsViewModel()) {
self.viewModel = viewModel
super.init(style: .Plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupBindings()
}
// MARK: - Private
private func setupBindings() {
tableView.dataSource = nil
viewModel.results
.bindTo(tableView.rx_itemsWithCellFactory) { tableView, row, result in
let cell: ShowResultCell = tableView.dequeueReusableCell(forRow: row)
cell.result = result
return cell
}
.addDisposableTo(disposeBag)
}
}
// MARK: - UISearchResultsUpdating
extension SearchResultsViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
viewModel.query.value = searchController.searchBar.text ?? ""
}
}
public protocol SearchResultsViewModelType: class {
/// The search query
var query: Variable<String> { get }
/// The search results
var results: Observable<[SearchResult.Show]> { get }
}
public class SearchResultsViewModel: SearchResultsViewModelType {
public let query: Variable<String> = Variable("")
public let results: Observable<[SearchResult.Show]>
public init(client: SearchClient = Client()) {
let minimumCharacterCount = 3
let dueTime = 0.3
results = query.asObservable()
.throttle(dueTime, scheduler: MainScheduler.instance)
.flatMapLatest { query in
(query.characters.count >= minimumCharacterCount)
? client.search(query, page: 1, type: .Ngram)
: Observable.just(Page())
}
.map { $0.items }
.catchErrorJustReturn([])
.observeOn(MainScheduler.instance)
.shareReplay(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment