2017-10-07 26 views
1

我有一个MapViewModel用于我的MapViewControllerViewModel中的链可观察值用于提取,但作为独立属性留下

我有一个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,以将地图对象显示为引脚和当前位置。

谢谢!

回答

0

你可以这样做:

事情是这样的:

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) 
} 
2

您可以定义mapObjects作为延续currentLocation可观察的currentLocation发出一个位置,它将用于拨打。

我在这里使用了flatMapLatest而不是flatMap,以便在呼叫结束之前发出新位置时放弃对fetchMapObjects的任何先前呼叫。

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

现在您只需订阅您的mapObjects可观测值并处理发射的任何MapObjects

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

感谢您的好解释。那样做了! – MayNotBe

+0

@MayNotBe不用客气!然而,为了公平起见,乔恩回答了我面前的问题,并基本上说了我所做的同样的事情。所以,如果你想,你可以标记他的答案,而不是我的答案。我会采取一个upvote也许? ;) – iska

+0

谢谢@iska!坦率地说,你的答案比我的好,至少应该得到另一个赞成。 – joern

相关问题