ios - 信号观察者能否访问 ReactiveCocoa 信号的最后发射值?

标签 ios swift reactive-programming reactive-cocoa reactive-cocoa-5

我开始使用 ReactiveCocoa,但我仍在为一些基本概念而苦苦挣扎:

  1. 我的应用程序开始监听地理位置数据(在我的 View 模型中为 init)
  2. 我的应用程序会发出带有我当前位置的信号(didFindCurrentPosition 被调用)
  3. 我的 View Controller 显示 map 加载(viewDidLoad 在我的 View Controller 中)
  4. 我的 View Controller 开始观察当前位置信号(仍然是 viewDidLoad)

我的问题是:完成第 2 步后,如果没有其他事件发送到信号上,我的 View Controller 就不会收到通知。

我的 View Controller 如何访问信号的最后一个值? (即如何在第 3 步访问第 2 步发出的值?)

感谢您的帮助。

PS:ReactiveCocoa 看起来像一个很棒的库,但我对文档的状态感到困惑。恕我直言,它不是很清楚,也缺乏一些关于如何使用它的明确指南。

代码

View 模型:

class MyViewModel: LocationManagerDelegate {
    let locationManager: LocationManager
    let geolocationDataProperty = MutableProperty<Geolocation?>(nil)
    let geolocationData: Signal<Geolocation?, NoError>

    init() {
        geolocationData = geolocationDataProperty.signal

        // Location Management
        locationManager = LocationManager()
        locationManager.delegate = self
        locationManager.requestLocation()
    }

    // MARK: - LocationManagerDelegate

    func didFindCurrentPosition(location: CLLocation) {
        geolocationDataProperty.value = Geolocation(location: location)
    }
}

View Controller :

class MyViewController: UIViewController {
    let viewModel = MyViewModel()

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.geolocationData
            .observe(on: UIScheduler())
            .observeValues { geolocation in
                debugPrint("GOT GEOLOCATION")
        }
    }
}

最佳答案

您已经有一个 Property 保存最新发出的值。不使用属性的 signal,而是使用 producer。这样,当您启动 producer 时,您将首先获得当前值(如果没有发送,您将获得 nil)。

比照。 the documentation :

The current value of a property can be obtained from the value getter. The producer getter returns a signal producer that will send the property’s current value, followed by all changes over time. The signal getter returns a signal that will send all changes over time, but not the initial value.

因此,关于问题中的代码,viewDidLoad 方法应该执行如下操作:

viewModel.geolocationDataProperty
        .producer
        .start(on: UIScheduler())
        .startWithValues { geolocation in
            debugPrint("GOT GEOLOCATION")
    }

关于ios - 信号观察者能否访问 ReactiveCocoa 信号的最后发射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813334/

相关文章:

ios - 为什么我的 dateFormatter 只能在 24 小时制设备设置下工作?

java - 错误时如何从Mono <A>返回Mono <B>?

angular - tap() 未在 RXJS 管道中触发

spring-boot - 响应式(Reactive)编程 : Spring WebFlux: How to build a chain of micro-service calls?

ios - 渐变不显示快速 Xcode

ios - 如何让 NSAssert 记录 Xcode4 中的描述?

swift - Swift 中停止动画 Canvas pod

objective-c - NSArray 搜索中的 NSDictionary

ios - RestKit:发送特定的 JSON,请帮忙,我已经尝试了我能想到的一切

ios - Xcode 11 更新后,Multipeer Connectivity 无法正常工作