Search code examples
swiftmvvmmapkitrx-swiftrx-cocoa

Chain observables in ViewModel for fetch but leave as independent properties


I have a MapViewModel for my MapViewController.

I have a MapObjectService with a function fetchMapObjects(currentLocation: CLLocation) that returns an Observable<MapObjects>

In the MapViewModel I have:

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

I can init the current location like this:

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

How can I efficiently init both properties so the fetchMapObjects() uses the currentLocation to set the mapObjects property?

My plan is to bind those properties to the mapView in MapViewController to show the map objects as pins and the current location.

Thanks!


Solution

  • You can do this:

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