gpt4 book ai didi

swift - 使用 flatMapLatest 合并两个流

转载 作者:行者123 更新时间:2023-11-28 14:11:10 26 4
gpt4 key购买 nike

在与 flatMapLatest 中的 observables 结合时遇到问题

逻辑:在每个事件的下一个事件上,我想将它与下一个 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 并不总是更新和返回旧值而不是新值

你们有什么想法吗?

最佳答案

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com