使用 flatMapLatest 合并两个流
Merge two streams with flatMapLatest
在与 flatMapLatest 中的 observables 结合时遇到问题
逻辑:在每个 activity 下一个事件中,我想将它与下一个 getCurrentLocation
事件结合在一起,该事件发生在 [=30= 之后]事件被触发,将它们连接成一个元组,然后用它做一些事情。
目前是这样
ActivitiesController
.start()
.flatMapLatest { activity in
LocationController.shared.getCurrentLocation().map { ([=10=], 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 [=10=] will refer to the current location that was just emitted and
// will refer to the last activityEvent that was emitted.
return ([=10=], )
}
在与 flatMapLatest 中的 observables 结合时遇到问题
逻辑:在每个 activity 下一个事件中,我想将它与下一个 getCurrentLocation
事件结合在一起,该事件发生在 [=30= 之后]事件被触发,将它们连接成一个元组,然后用它做一些事情。
目前是这样
ActivitiesController
.start()
.flatMapLatest { activity in
LocationController.shared.getCurrentLocation().map { ([=10=], 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 [=10=] will refer to the current location that was just emitted and
// will refer to the last activityEvent that was emitted.
return ([=10=], )
}