ViewModel中的链可观察值用于提取,但作为独立属性留下
问题描述:
我有一个MapViewModel
用于我的MapViewController
。ViewModel中的链可观察值用于提取,但作为独立属性留下
我有一个MapObjectService
与函数fetchMapObjects(currentLocation: CLLocation)
返回一个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
属性?
我的计划是将这些属性绑定到MapViewController
中的mapView,以将地图对象显示为引脚和当前位置。
谢谢!
答
你可以这样做:
事情是这样的:
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 = 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)
}
答
您可以定义mapObjects
作为延续currentLocation
流可观察的currentLocation
发出一个位置,它将用于拨打。
我在这里使用了flatMapLatest
而不是flatMap
,以便在呼叫结束之前发出新位置时放弃对fetchMapObjects
的任何先前呼叫。
您还可以在flatMapLatest
之前为currentLocation
定义过滤条件,以防您想忽略其中的一些条目,例如,当距离与前一个距离太短时。
现在您只需订阅您的mapObjects
可观测值并处理发射的任何MapObjects
。
mapObjects.subscribe(onNext: { objects in
// handle mapObjects here
})
感谢您的好解释。那样做了! – MayNotBe
@MayNotBe不用客气!然而,为了公平起见,乔恩回答了我面前的问题,并基本上说了我所做的同样的事情。所以,如果你想,你可以标记他的答案,而不是我的答案。我会采取一个upvote也许? ;) – iska
谢谢@iska!坦率地说,你的答案比我的好,至少应该得到另一个赞成。 – joern