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

Posted

技术标签:

【中文标题】如何在带有 RxSwift 的驱动程序上使用 flatMapLatest【英文标题】:How to use flatMapLatest on a driver with RxSwift 【发布时间】:2019-02-09 12:38:08 【问题描述】:

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

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<_, _>'

我在这里做错了什么?

【问题讨论】:

【参考方案1】:

您将.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: [])
        )
()

【讨论】:

啊!是的,最后。非常感谢。不过,我仍然无法完全理解 Drivers .. 任何与最新 RxSwift 保持同步的好资源?

以上是关于如何在带有 RxSwift 的驱动程序上使用 flatMapLatest的主要内容,如果未能解决你的问题,请参考以下文章

如何在 RxSwift 中为整个应用程序中的单元格和按钮设置动画?

如何在 RxSwift 中过滤带有按钮标题的按钮点击?

RxSwift:如何通过多个视图模型传递控制事件

如何将多个驱动程序与 RxSwift 正确组合?

RxSwift + UITableViewCell 如何在 heightForRowAt 中获取单元格对象

带有 UITextFieldDelegate 的 RxSwift 控制事件