使用flatMapLatest合并两个流

时间:2018-09-26 09:04:16

标签: swift rx-swift reactive-cocoa reactive

在flatMapLatest中与可观察对象结合存在问题

逻辑:在每个活动下一个事件上,我都希望将其与下一个getCurrentLocation事件(在activityEvent触发后发生)结合在一起,将它们加入一个元组,然后执行有东西。

当前就是这样

ActivitiesController
    .start()
    .flatMapLatest { activity in 
        LocationController.shared.getCurrentLocation().map { ($0, activity) }
    }
    .subscribe(onNext: { (activity, currentLocation in
        print("")
    })
    .disposed(by: disposeBag)

位置代码:

func getCurrentLocation() -> Observable<CLLocation> {
    self.requestLocationUseAuthorizationIfNotDetermined(for: .always)
    self.locationManager.requestLocation()
    return self.publishSubject.take(1) // take next object from the publish subject (only one)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last, location.horizontalAccuracy > 0 else {
        return
    }
    self.publishSubject.onNext(location)
}

由于我们知道requestLocation()会触发didUpdateLocations,因此我们认为该逻辑应该起作用,但事实并非如此

结果是locationManager并不总是更新并返回旧值而不是新值

你们有什么主意吗?

1 个答案:

答案 0 :(得分:1)

您需要使用withLatestFrom而不是flatMapLatest

LocationController.shared.getCurrentLocation().withLatestFrom(activityEvent) {
    // in here $0 will refer to the current location that was just emitted and
    // $1 will refer to the last activityEvent that was emitted.
    return ($0, $1)
}