与flatMapLatest中的可观测数据相结合有问题
逻辑:在每个activity next事件上,我想将它与下一个getCurrentLocation事件组合在一起,后者发生在activity event被触发之后,将它们组合在一个元组中,然后对其进行处理。
现在是这样

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()触发了diddupdatelocations,所以我们认为逻辑应该工作,但它不工作
结果是locationManager并不总是更新和返回旧值而不是新值
你们知道吗?

最佳答案

您需要使用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)
}

关于swift - 使用flatMapLatest合并两个流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52513888/

10-11 21:48