gpt4 book ai didi

swift - 如何在带有 RxSwift 的驱动程序上使用 flatMapLatest

转载 作者:搜寻专家 更新时间:2023-11-01 06:54:23 26 4
gpt4 key购买 nike

每当我的用户位置发生变化时,我都会尝试从网络中获取一些数据。

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: [])
})
}()

关于swift - 如何在带有 RxSwift 的驱动程序上使用 flatMapLatest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com