Forked from gonzalezreal/SearchResultsViewController.swift
Created
June 12, 2016 23:46
-
-
Save acecilia/8bc55cf3acb7269ee98106ce7bea86e3 to your computer and use it in GitHub Desktop.
RxSwift slides – Code for the search sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ?? "" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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