[英]How to use flatMapLatest on a driver with RxSwift
I'm trying to fetch some data from the network whenever the location of my user changes. 每当用户位置更改时,我都试图从网络中获取一些数据。
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
}
However, this is not compiling, due to: 但是,由于以下原因,该文件未编译:
Cannot convert value of type 'SharedSequence<DriverSharingStrategy, [Any]>' to specified type 'Driver<[City]>'
(aka 'SharedSequence<DriverSharingStrategy, Array<City>>')
I've also tried to add some Type hinting to get a better error: 我还尝试添加一些类型提示以获取更好的错误:
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]())
}()
But all that gives me is: 但是,所有给我的是:
Cannot convert value of type '(_) -> Observable<[City]>' to expected argument type '(CLLocationCoordinate2D) -> SharedSequence<_, _>'
What am I doing wrong here? 我在这里做错了什么?
You are putting the .asDriver
call in the wrong place. 您将.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: [])
})
}()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.