【问题标题】:Merge two streams with flatMapLatest使用 flatMapLatest 合并两个流
【发布时间】:2018-09-26 09:04:15
【问题描述】:

在 flatMapLatest 中与 observable 组合时遇到问题

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

你们有什么想法吗?

【问题讨论】:

  • 尝试打印出位置数组并检查其内容。也许位置变化不足以被检测到。我不知道 publishSubject.take() 是如何工作的,但它似乎在 requestLocation 完成之前返回。这是你想要的行为吗?

标签: swift rx-swift reactive-cocoa reactive


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 2014-05-23
    • 2013-12-30
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2020-03-20
    • 2023-03-26
    • 2018-05-02
    相关资源
    最近更新 更多