swift - 如何在带有 RxSwift 的驱动程序上使用 flatMapLatest
问题描述
每当我的用户位置发生变化时,我都会尝试从网络中获取一些数据。
struct CityService {
private init() {}
static let shared = CityService()
lazy var nearbyCities: Driver<[City]> = {
return GeolocationService.instance.location
.flatMapLatest({ coordinate in
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
return CityService.shared.fetchNearbyCitiesFor(location)
}).asDriver(onErrorJustReturn: [])
}()
func fetchNearbyCitiesFor(_ location: CLLocation) -> Observable<[City]> {
return Observable.create { observer in
let disposable = Disposables.create()
// Mock a fetch from the network:
let cities = [City(name: "Amsterdam"), City(name: "Berlin")]
observer.onNext(cities)
observer.on(.completed)
return disposable
}
}
}
class GeolocationService {
static let instance = GeolocationService()
private (set) var location: Driver<CLLocationCoordinate2D>
}
// from: https://github.com/ReactiveX/RxSwift/blob/master/RxExample/RxExample/Services/GeolocationService.swift
struct City {
let name: String
}
但是,这不是编译,因为:
Cannot convert value of type 'SharedSequence<DriverSharingStrategy, [Any]>' to specified type 'Driver<[City]>'
(aka 'SharedSequence<DriverSharingStrategy, Array<City>>')
我还尝试添加一些类型提示以获得更好的错误:
lazy var nearbyCities: Driver<[City]> = {
return GeolocationService.shared.location
.flatMapLatest({ coordinate -> Observable<[City]> in
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
let nearbyCities: Observable<[City]> = CityService.shared.fetchNearbyCitiesFor(location)
return nearbyCities.catch
}).asDriver(onErrorJustReturn: [City]())
}()
但给我的只是:
Cannot convert value of type '(_) -> Observable<[City]>' to expected argument type '(CLLocationCoordinate2D) -> SharedSequence<_, _>'
我在这里做错了什么?
解决方案
你把.asDriver
电话打错了地方。
lazy var nearbyCities: Driver<[City]> = {
return GeolocationService.instance.location
.flatMapLatest({ (coordinate) -> Driver<[City]> in
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
return CityService.shared.fetchNearbyCitiesFor(location)
.asDriver(onErrorJustReturn: [])
})
}()
推荐阅读
- python - 这是使用openpyxl删除Excel行的更快方法吗?
- python - Python,从类方法中删除列表项
- javascript - 在 index.html 中使用来自 cdn 链接的 React 组件
- javascript - 如果 JavaScript 对象具有相同的键不同的值,则只获取重复键的最后一个键值
- vba - 搜索带有今天日期和特定主题的已发送项目
- python - SessionNotCreatedException:消息:未从选项卡创建的会话在 Python 中使用 Odoo 崩溃,但 selenium 单独工作正常,
- javascript - 仅对来自 React 中的 api 响应的对象数组中的几个对象进行排序
- javascript - 范围问题 - 在子实例中的 $emit 事件后未定义注入的父类
- c++ - 有没有办法在 C++ 的 IF 语句中检查迭代器是否是 random_access?
- javascript - 无法将任何内容从 bit.dev 导入我的 React 项目