我目前正在使用 Moya 发出网络请求。我已经从示例项目之一实现了以下内容@https://github.com/DroidsOnRoids/RxSwiftExamples#tutorials https://github.com/DroidsOnRoids/RxSwiftExamples#tutorials
下面我设置了restaurantSearch,以便当有人输入文本时它会发出新请求。
var restaurantSearch: Observable<(String)> {
return searchBar
.rx_text
.throttle(0.5, scheduler: MainScheduler.instance)
.distinctUntilChanged()
}
我有一个返回 [Restaurant] 类型的可观察值的方法
func restaurants() -> Observable<[Restaurant]> {
return restaurantSearch
.observeOn(MainScheduler.instance)
.flatMapLatest { postcode -> Observable<[Restaurant]?> in
return self.getRestaurants(postcode, cuisine: "", restaurantName: "")
}.replaceNilWith([])
}
internal func getRestaurants(postcode: String, cuisine: String, restaurantName: String) -> Observable<[Restaurant]?> {
return self.justEatProvider
.request(.Restaurant(postcode, cuisine, restaurantName))
.debug()
.mapArrayOptional(Restaurant.self, keyPath: "Restaurants")
}
我正在调用此方法并将其绑定到 tableView,如下所示:
func setupRx() {
api = JustEatApi(provider: provider, restaurantSearch: restaurantSearch)
api
.restaurants()
.bindTo(tableView.rx_itemsWithCellIdentifier("RestaurantTableViewCell", cellType: RestaurantTableViewCell.self)) { (row, element, cell) in
cell.restaurant = element
}
.addDisposableTo(disposeBag)
}
这工作正常。如果我输入邮政编码,它会进行搜索并填充 tableView。
如果我关闭互联网并尝试更改邮政编码,则 tableView 保持原样。但是,当我滚动时,它会使我的应用程序崩溃,并显示以下内容:
@noreturn func rxFatalError(lastMessage: String) {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
另外,如果我不滚动,而是返回互联网并更改邮政编码,则什么也不会发生。似乎已经失去了束缚。
首先我尝试在之前添加 catchOnErrorbindTo
方法调用,但我在评论中读到它不应该作为 UIBinding 的一部分处理:http://blog.scottlogic.com/2014/05/11/reactivecocoa-tableview-binding.html http://blog.scottlogic.com/2014/05/11/reactivecocoa-tableview-binding.html
我想我应该在方法中处理它:
func restaurants() -> Observable<[Restaurant]> {
return restaurantSearch
.observeOn(MainScheduler.instance)
.flatMapLatest { postcode -> Observable<[Restaurant]?> in
return self.getRestaurants(postcode, cuisine: "", restaurantName: "")
}.replaceNilWith([])
}
所以我有两个问题:
1) 我应该在哪里以及如何处理网络错误?
2)为什么我重新上网后tableView没有更新?
非常感谢任何帮助。