簡體   English   中英

如何在具有RxSwift的驅動程序上使用flatMapLatest

[英]How to use flatMapLatest on a driver with RxSwift

每當用戶位置更改時,我都試圖從網絡中獲取一些數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM