Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acecilia/8bc55cf3acb7269ee98106ce7bea86e3 to your computer and use it in GitHub Desktop.
Save acecilia/8bc55cf3acb7269ee98106ce7bea86e3 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