所以我一直在研究RxSwift几天,并且正在尝试用它创建一个简单的应用程序。我已将表的searchController绑定到结果,该结果将馈入cellForRowAt
函数中。如何将alamofire反应绑定到每个细胞?
我需要做什么?
Variable
并使用toObservable
?response
或searchResultsArray
以创建每个单元格。我需要使用的功能是:
.bind(to: self.tableView.rx.items(cellIdentifier: "cell", cellType: UITableViewCell.self)) { row, element, cell in
cell.textLabel?.text = "something"
}
这是我当前的RxSwift代码:
let disposeBag = DisposeBag()
var searchResultsArray = [[String:String]]()
searchController.searchBar.rx.text.orEmpty.filter { text in
text.count >= 3
}.subscribe(onNext: { text in
searchRequest(search: text, searchType: "t:t") { response in
self.searchResultsArray = response
self.tableView.reloadData()
}
}).disposed(by: disposeBag)
这是我当前的单元格创建功能。单击取消按钮后showSearchResults
会发生变化。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
return UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
}
return cell
}()
if self.shouldShowSearchResults {
cell.textLabel?.text = searchResultsArray[indexPath.row]["result"]!
cell.detailTextLabel?.text = searchResultsArray[indexPath.row]["location"]!
}
return cell
}
这是我当前的api请求:
func searchRequest(search: String, searchType: String, completionHandler: @escaping ([[String: String]]) -> ()) {
let payload: [String: Any] = [
"q": search,
"fq": searchType,
"start": 0
]
let url = URL(string: "https://www.athletic.net/Search.aspx/runSearch")!
Alamofire.request(url, method: .post, parameters: payload, encoding: JSONEncoding.default).responseJSON { response in
let json = response.data
do {
var searchResults: [[String: String]] = []
let parsedJson = JSON(json!)
if let doc = try? Kanna.HTML(html: parsedJson["d"]["results"].stringValue, encoding: .utf8) {
for row in doc.css("td:nth-child(2)") {
let link = row.at_css("a.result-title-tf")!
let location = row.at_css("a[target=_blank]")!
let schoolID = link["href"]!.components(separatedBy: "=")[1]
searchResults.append(["location": location.text!, "result": link.text!, "id":schoolID])
}
}
completionHandler(searchResults)
} catch let error {
print(error)
}
}
}
我想用RxSwift解决方案替换cellForRowAt。
答案 0 :(得分:2)
根据您提供的代码,使用Rx将为您提供以下信息:
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchBar.rx.text.orEmpty
.filter { text in text.count >= 3 }
.flatMapLatest { text in searchRequest(search: text, searchType: "t:t") }
.bind(to: self.tableView.rx.items(cellIdentifier: "cell", cellType: UITableViewCell.self)) { row, element, cell in
if self.shouldShowSearchResults {
cell.textLabel?.text = element["result"]!
cell.detailTextLabel?.text = element["location"]!
}
}
.disposed(by: disposeBag)
}
shouldShowSearchResults
在那感觉不合时宜。但是否则看起来不错。
以上假设您将searchRequest包装在一个函数中,该函数返回如下所示的可观察值:
func searchRequest(search: String, searchType: String) -> Observable<[[String: String]]> {
return Observable.create { observer in
searchRequest(search: search, searchType: searchType, completionHandler: { result in
observer.onNext(result)
observer.onCompleted()
})
return Disposables.create()
}
}
上面是一个标准模式,它将使用回调的函数包装到返回Observable
的函数中。