如何在具有RxSwift的驱动程序上使用flatMapLatest

时间:2019-02-09 12:38:08

标签: swift reactive-programming rx-swift rx-cocoa

每当用户位置更改时,我都试图从网络中获取一些数据。

lag

但是,由于以下原因,该文件未编译

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

我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

您将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: []) }) }() 呼叫放在错误的位置。

<meta name="csrf-token" content="{{csrf_token()}}">