2017-10-07 34 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

相關問題