链接视图模型中的可观察量以进行提取,但保留为独立属性



我有一个MapViewController MapViewModel

我有一个带有函数fetchMapObjects(currentLocation: CLLocation)MapObjectService,该函数返回Observable<MapObjects>

在MapViewModel中,我有:

var currentLocation: Observable<CLLocation?>
var mapObjects: Observable<MapObjects>

我可以像这样初始化当前位置:

currentLocation = locationManager.rx.didUpdateLocations.map( { locations in
        return locations.filter() { loc in
            return loc.horizontalAccuracy < 20
            }.first
    })

如何有效地初始化这两个属性,以便fetchMapObjects()使用 currentLocation 来设置mapObjects属性?

我的计划是将这些属性绑定到 mapView 中 MapViewController,以将地图对象显示为图钉和当前位置。

谢谢!

您可以将

mapObjects定义为currentLocation流的延续

像这样:

currentLocation = locationManager.rx.didUpdateLocations.map { locations in
    return locations.first(where: { location -> Bool in
        return location.horizontalAccuracy < 20
    })
}
mapObjects = currentLocation.flatMapLatest { location -> Observable<MapObjects> in
    guard let location = location else {
        return Observable<String>.empty()
    }
    return fetchMapObjects(currentLocation: location)
}

这样,每次currentLocation可观察量发出一个位置时,它都将用于fetchMapObjects调用。

我在这里使用了flatMapLatest而不是flatMap,以便在调用完成之前发出新位置时丢弃以前对fetchMapObjects的任何调用。

您还可以在flatMapLatest之前为currentLocation定义过滤,以防您想忽略其中一些,例如,当距离与前一个距离太短时。

现在,您只需订阅可观察mapObjects并处理发出的任何MapObjects即可。

mapObjects.subscribe(onNext: { objects in
    // handle mapObjects here
})

你可以这样做:

currentLocation = locationManager.rx.didUpdateLocations.map( { locations in
   return locations.filter() { loc in
      return loc.horizontalAccuracy < 20
   }.first
})
mapObjects = currentLocation.flatMap { loc in
   return MapObjectService.fetchMapObjects(currentLocation: loc)
}

最新更新