Skip to content

Instantly share code, notes, and snippets.

@mcichecki
Created August 17, 2018 16:22
Show Gist options
  • Save mcichecki/37d3b96bade4e007e5c6373372d761c2 to your computer and use it in GitHub Desktop.
Save mcichecki/37d3b96bade4e007e5c6373372d761c2 to your computer and use it in GitHub Desktop.
UISearchResultsUpdating proxy for UISearchController with RxSwift and RxCocoa
import RxCocoa
import RxSwift
public extension Reactive where Base: UISearchController {
var delegate: DelegateProxy<UISearchController, UISearchResultsUpdating> {
return RxSearchResultsUpdatingProxy.proxy(for: base)
}
var searchPhrase: Observable<String> {
return RxSearchResultsUpdatingProxy.proxy(for: base).searchPhraseSubject.asObservable()
}
}
import RxCocoa
import RxSwift
import UIKit
class RxSearchResultsUpdatingProxy: DelegateProxy<UISearchController, UISearchResultsUpdating>, UISearchResultsUpdating {
lazy var searchPhraseSubject = PublishSubject<String>()
init(searchController: UISearchController) {
super.init(parentObject: searchController, delegateProxy: RxSearchResultsUpdatingProxy.self)
}
func updateSearchResults(for searchController: UISearchController) {
searchPhraseSubject.onNext(searchController.searchBar.text ?? "")
}
}
extension RxSearchResultsUpdatingProxy: DelegateProxyType {
static func currentDelegate(for object: UISearchController) -> UISearchResultsUpdating? {
return object.searchResultsUpdater
}
static func setCurrentDelegate(_ delegate: UISearchResultsUpdating?, to object: UISearchController) {
object.searchResultsUpdater = delegate
}
static func registerKnownImplementations() {
register { RxSearchResultsUpdatingProxy(searchController: $0) }
}
}
// how to use
searchController.rx.searchPhrase
.subscribe(onNext: { [weak self] in
self?.filterResults(for: $0)
}).disposed(by: disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment