我有一个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)
}